I am trying to develop ratings for my application, where a User is able to set a specific rating for a comment. I have followed the following tutorial in order to do so.
Here are my associations:
class Rating < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end
class Comment < ActiveRecord::Base
has_many :ratings
belongs_to :user
end
class User < ActiveRecord::Base
has_many :ratings
has_many :comments
end
My problem here is that, in the index action of my comments controller, I need to include the rating that the user has done for that comment. In the tutorial is just shown how to select a particular rating by doing this:
@rating = Rating.where(comment_id: @comment.id, user_id: @current_user.id).first
unless @rating
@rating = Rating.create(comment_id: @comment.id, user_id: @current_user.id, score: 0)
end
However, I will have several ratings, because in my controller I have:
def index
@comments = @page.comments #Here each comment should have the associated rating for the current_user, or a newly created rating if it does not exist.
end