11

if my database is set to as false, whats the best practice in updating boolean value in database?

I can do it on console:

>> u = User.find_by_id(1)

What do I do next?

Thanks

2 Answers 2

18

If you want to toggle the boolean:

u.toggle!(:<attribute>)  # Toggles the boolean and saves without validations
u.toggle(:<attribute>)   # Toggles the boolean and does not save

If you want to set the boolean:

u.<attribute> = [true|false]

If you want to update the boolean immediately:

u.update_column(:<attribute>, [true|false])  # Doesn't update timestamps or call callbacks
u.update_attribute(:<attribute>, [true|false])  # Updates timestamps and triggers any callbacks
Sign up to request clarification or add additional context in comments.

2 Comments

this usage gives an error, you should use u.toggle!(<attribute>)
Thanks, @Serhan. Fixed
0
>> u.boolean_property = false
>> u.save

where boolean_property is the name of the property that you want to set to false.

That is the simplest way (just setting it directly), and there are other ways, depending on your needs: http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/

1 Comment

im actually trying this in heroku, i'm in heroku run console and its saying undefined method 'boolean_property. Also, I'm trying to update it to true

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.