Validates :presence

Hello, comrads!

I can’t understand some thing.

For example, I have a table(mysql), which includes boolean field named
:truly . Model name is Test

I create a validation: validates :truly, :presence => true

When I add information:

Test.valid?(… :truly => true, …) it’s ok, but when I write:
Test.valid?(… :trule => false, …) I read same error:

{:truly=>[“can’t be blank”]} . But it isn’t blank, it’s value - false!
What I must to do to fix this?

So, I create a decision:

validate :true_or_false

when true_or_false:

def true_or_false
errors.add(:truly, “Truly mustn’t be nil”) if truly == nil
end

Are better decisions exist?

Thanks in advance, MO

Misha O. wrote in post #1007017:

I can’t understand some thing.

For example, I have a table(mysql), which includes boolean field named
:truly . Model name is Test

I create a validation: validates :truly, :presence => true

When I add information:

Test.valid?(… :truly => true, …) it’s ok, but when I write:
Test.valid?(… :trule => false, …) I read same error:

{:truly=>[“can’t be blank”]} . But it isn’t blank, it’s value - false!
What I must to do to fix this?

The BOOL data type in MySQL is an alias for TINYINT. This means that
MySQL stores boolean data in an 8-bit integer field where 0 is false and
1 is true. Given this, MySQL BOOL fields have three states:

  1. A value representing false
  2. A value representing true
  3. The NULL value

What I do in most situations is prevent NULL values on BOOL columns at
the database level. In Rails you can specify this in the migration:

t.boolean :obsolete, :null => false, :default => false

Using this technique eliminates the need to validate presence of boolean
fields. That is enforced at the database level.