Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails presence validation fails on value 0

I have a model similar to the following,

class Activity < ActiveRecord::Base
    attr_accessible :name, :admin

    validates :name, :presence => true
    validates :admin, :presence => true
end 

The name property is a string and the admin property is defined as a boolean in the migration.

If I try to create an instance of the model in the console using,

a = Activity.create(:name => 'Test', :admin => 0)

Then the validation fails saying I need to provide a value for Admin. Why? I have supplied a value.

I could understand if I had failed to supply a value at all or if I had supplied nil. But why does a value like 0 (or even false for that matter) cause validation to fail?

like image 468
richard Avatar asked Nov 05 '12 05:11

richard


2 Answers

validates :presence uses blank? to determine whether a value is present. But false.blank? => true. So the validation fails, because blank? is telling ActiveRecord that no value is present.

You can rewrite this as:

validates :field_name, :inclusion => { :in => [true, false] }

as recommended in Rails Guides: ActiveRecord Validations

see also A concise explanation of nil v. empty v. blank in Ruby on Rails

like image 102
zetetic Avatar answered Sep 28 '22 18:09

zetetic


Rails 4/5

validates :name, absence: true
like image 21
pmargreff Avatar answered Sep 28 '22 18:09

pmargreff