Convert a check box value to a boolean

Most of the time when I create a model with a boolean attribute I don’t actually
use a boolean in the database. A popular example is published on a blog post,
being implemented via setting the publish_date.

This means that in Rails to use form_for you just need to define the accessors
on the model and everything should work, except it doesn’t because the form
returns “0” for false and “1” for true, as strings. A real ActiveRecord model
gets around this by converting the values to boolean before setting. Since it is
tedious to implement time and time again it is easy to just reuse the Rails
internal function.


=> false


=> true

Quick and easy!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.