Super Spread Sheet S³

Or little computing tricks and hacks

Data Validation of boolean values in Rails

To validating the presence of a boolean value, the short answer is you don’t need to. Rails does an automatic check on boolean data types.

In theory validating the presence would be just a waste of time, but in practice it creates a bug. If you have in your model.rb a line similar to

validates :is_active, presence: true

and is_active is a boolean, when entering false as a value, Rails interprets it as empty and the action of creating or updating the record is refused.

Leaving the line out will allow the creation or updating of the record and if the value is not either true or false, the stored value will be nil.

You may want to ensure that the value is either true or false. In that case, the following line should be added:

validates_inclusion_of :active, :in => [true, false]

Inspired from:

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: