我正在跟随schneems关于创建Reddit克隆的Rails tutorial的伟大介绍,并想扩展“投票”结构,不仅适用于问题,也适用于评论,并且很难弄清楚如何将question_id和comment_id都传递到控制器中,以便它可以相应地投票赞成或反对,而不是将使用限制为只使用question_id。
目前我的VotesController中只有一个create函数,定义如下:
def create
@vote = Vote.where(:question_id => params[:vote][:question_id], :user_id => current_user.id).first #the question_id is baked right in..
if @vote
@vote.up = params[:vote][:up]
@vote.save
else
@vote = current_user.votes.create(params[:vote])
end
redirect_to :back
end谢谢你的帮忙!
发布于 2013-01-19 07:00:07
那么,当您尝试对评论进行投票时,这意味着params[:vote]应该包含:comment_id而不是:question_id,对吧?
因此,您的where语句需要
# for a question
where(:question_id => params[:vote][:question_id], :user_id => current_user.id)
# for a comment
where(:comment_id => params[:vote][:comment_id], :user_id => current_user.id)您可以通过各种方式来实现这一点,比如检查是否为params[:vote].has_key?(:question_id),但一个简单的选择是使用Hash#slice
where(params[:vote].slice(:question_id, :comment_id).merge(:user_id => current_user.id))https://stackoverflow.com/questions/14408866
复制相似问题