【发布时间】:2014-05-29 21:54:14
【问题描述】:
我正在尝试为我的应用程序开发评级,用户可以在其中为评论设置特定评级。为了做到这一点,我遵循了以下tutorial。
这是我的联想:
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
我的问题是,在我的 cmets 控制器的索引操作中,我需要包含用户对该评论所做的评分。在教程中只展示了如何通过这样做来选择特定的评级:
@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
但是,我会有几个评分,因为在我的控制器中我有:
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
【问题讨论】:
标签: ruby-on-rails associations rating