Reputation: 23
Why do I get this error? I'm out of ideas.
undefined method `update_attributes' for #
Code:
exists = Vote.where(comment_id: @comment.id).exists?
if exists
update_vote = Vote.where(comment_id: @comment.id)
update_vote.update_attributes(value: 5)
redirect_to :back
else
Upvotes: 2
Views: 3620
Reputation: 319
Try using find_by
instead of where
. It will return one document instead of a Mongoid::Criteria
, which is why you're getting that error (you're trying to run .update_attributes
, which acts on a single record, on a group of records). Consider the following instead.
if update_vote = Vote.find_by(comment_id: @comment.id)
update_vote.update_attributes(value: 5)
redirect_to :back
else
The above code can also avoid an unnecessary call to .exists?
since the existence check is right along with the definition (if .find_by
does not find any records that match, it returns nil
, much like .where(...).first
would also do).
Upvotes: 1
Reputation: 115541
You want to fetch one record in particular, so tell it:
update_vote = Vote.where(comment_id: @comment.id).first
but this code is prone to errors if nothing matches, beware.
Upvotes: 8