Validating Boolean Value of False in Rails

I came across a bit of a weird one this afternoon when trying to validate. Several of my fields appeared to be incorrectly flagged as not having a value.

This is the validation I was using:

#Define validation
validates :order_id, :user_id, :acknowledged, :completed, :presence => true

 

The fields that were flagging as not present were :acknowledged and completed. After hardcoding the values and still not getting anywhere I realised that while values were being provided, they were boolean values of false. Apparently :presence will treat a value of false as not being present.

After another Google search I came across this post which shows how to validate a boolean value.

When implemented within my app, the new validation looks like this:

#Define validation
validates :order_id, :user_id, :presence => true
validates :acknowledged, :completed, :inclusion => {:in => [true, false]}

Hopefully that’ll be able to help a few of you out as well.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s