Reputation:
I'm trying to create a new object that is related to two other models but I'm having a hard time getting it to work.
The model is:
class Vote < ActiveRecord::Base
belongs_to :solution
belongs_to :user
end
(The solution and user model both have has_many :votes
on their side.
In my solutions controller I'm doing this:
def process_vote
solution = Solution.find(params[:id])
vote = Vote.where(:user => current_user, :solution => solution)
if(vote.count == 0)
newvote = Vote.new
newvote.user = current_user
newvote.positive = true
newvote.solution = solution
newvote.save
end
respond_to do |format|
format.js {
render :nothing => true
}
end
end
The query generated by ActiveRecord is looking for the wrong columns though, this is what console shows when I call the process_vote
method:
(0.6ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`user` = 2 AND `votes`.`solution` = 5
Mysql2::Error: Unknown column 'votes.user' in 'where clause': SELECT COUNT(*) FROM `votes` WHERE `votes`.`user` = 2 AND `votes`.`solution` = 5
Completed 500 Internal Server Error in 17ms
ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'votes.user' in 'where clause': SELECT COUNT(*) FROM `votes` WHERE `votes`.`user` = 2 AND `votes`.`solution` = 5):
app/controllers/solutions_controller.rb:74:in `process_vote'
Any ideas what could be wrong? It seems to me that the relations are set up fine. The actual column names are user_id
and solution_id
.
Upvotes: 0
Views: 830
Reputation: 729
where
. Use ID'sSo your action should looks like this:
def process_vote
current_user.votes << Vote.new(:positive => true, solution_id => params[:id]) if current_user.votes.where(:solution_id => params[:id]).count == 0
respond_to do |format|
format.js {
render :nothing => true
}
end
end
Upvotes: 0
Reputation: 1533
vote = Vote.where(:user_id => current_user.id, :solution_id => solution.id)
Upvotes: 3