My controller action:
def updating_rating
input = params[:recommendation_ratings].values
input.each do |mini_params|
rating_id = mini_params[:rating_id].to_i
recommendation_id = mini_params[:recommendation_id].to_i
puts rating_id
puts recommendation_id
rr = RecommendationRating.find_or_create_by_rating_id_and_recommendation_id(rating_id, recommendation_id)
rr.update_attributes(:rating_id => rating_id, :recommendation_id => recommendation_id )
end
redirect_to :back, :flash => { :notice => "Rating Submitted." }
end
I am passing in the params from a form_tag in my view. The code works as expected when creating a new relationship, however if you try to update a value and resubmit the form, it adds a new rating, rather that updating the existing rating.
So for example if you have a product with a rating of 1, and change the rating to 2 and resubmit the form, that product will have ratings of 1 and 2. What do I do to update an existing rating, rather than adding an additional rating to a product.
I’m assuming that rating_id is the actual rating that you want to save. With this assumption in mind,
will find first a
RecommendationRatingwhich has arating_idof the new rating value. If it can’t find any it will create one. You can fix this by just finding aRecommendationRatingfirst and build a new one if it’s not existingIf you have associations, it will look cleaner (i’m assuming a
has_onerelationship here because we’re only talking about 2 columns)