Reputation: 5495
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!
Upvotes: 0
Views: 107
Reputation: 6644
Well, when you try to vote on a comment, that would mean that params[:vote]
should contain a :comment_id
instead of a :question_id
, right?
So your where
statement needs to either be
# 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)
You approach this in various ways, like by checking if params[:vote].has_key?(:question_id)
, but an easy option would be to use Hash#slice
:
where(params[:vote].slice(:question_id, :comment_id).merge(:user_id => current_user.id))
Upvotes: 1