6

I am trying to add one to the already incremented field in the DB, but I am getting the following error: NoMethodError (undefined method+' for false:FalseClass):`

Code:

med = Media.find(params[:media_id])
med.update_attributes({:screener_viewed => med.screener_viewed + 1})

I am just wanting to add 1 to the current value of screener_viewed, but can't get it to work.

Working Code:

Media.increment_counter(:screener_viewed, params[:media_id])

4 Answers 4

16

Use increment!:

med.increment!(:screener_viewed)

Make sure that screener_viewed is of type integer in your db.

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

2 Comments

I actually just found this after refining my Google search! I am still new to Rails and I have no idea where it has been ALL my life, but I am definitely loving every minute of it! Thanks for the help!
Glad this helped. Rails is definitely an eye-opener. I would advise you to also learn more about ruby itself. The awesomeness of Rails is in large part due to the "ruby way".
0

Examine the error message carefully. It says there is no addition method defined for the FalseClass, which means that screener_viewed contains a boolean value of false. Did you expect it to contain an integer, or are you trying to flip the value to true?

Comments

0

Could you provide the migration definition for the Media model? It looks like you've defined it as a Boolean, which does not support the + operator:

irb(main):002:0> false + 1
NoMethodError: undefined method `+' for false:FalseClass
        from (irb):2

Comments

0

Careful about using increment! I does not support concurrent request.

http://apidock.com/rails/ActiveRecord/Base/increment!

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.