I am following schneems’s great intro to Rails tutorial on creating a Reddit clone, and want to expand the “voting” structure to work not only for questions, but for comments as well, and was having difficulty figuring out how to pass into the controller both question_id and comment_id so it could vote up or down accordingly, rather than restricting the usage to only question_id.
Currently, there is only a create function in my VotesController, defined as the following:
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
Thanks for your help!
Well, when you try to vote on a comment, that would mean that
params[:vote]should contain a:comment_idinstead of a:question_id, right?So your
wherestatement needs to either beYou approach this in various ways, like by checking if
params[:vote].has_key?(:question_id), but an easy option would be to useHash#slice: