2

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
1
  • What this error message tells you is that your update_vote.update_attributes is not defined. Somewhere earlier in your code, you should define update_attributes, otherwise you can't use it here. Commented Jan 27, 2014 at 22:10

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.