user3237279
user3237279

Reputation: 23

Undefined method `update_attributes'?

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

Answers (2)

take
take

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

apneadiving
apneadiving

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

Related Questions