10

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?

richard
  • 1,565
  • 2
  • 18
  • 35

2 Answers2

21

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

Community
  • 1
  • 1
zetetic
  • 47,184
  • 10
  • 111
  • 119
  • Makes sense to me I guess. But I guess I still don't agree that false.blank? or 0.blank? should return true – richard Nov 05 '12 at 05:37
  • Fair enough, but you'll have to take that up with the guys who wrote Rails :) – zetetic Nov 05 '12 at 06:05
  • +1. The solution works. But I too wish Rails handled this better. The error message when using the solution here is `:upgraded_kitchen_bathrooms=>["is not included in the list"]` which is horrible considering the simplicity of what we're after. – Tyler Collier Nov 16 '13 at 00:18
  • 1
    Well it was pretty easy to fix my complaint about the error message: http://stackoverflow.com/a/7011116/135101 – Tyler Collier Nov 16 '13 at 00:22
  • I agree that false.blank? is not the same as "is a value present?" Thanks for posting this, finally it makes sense! – vanboom Apr 08 '14 at 01:35
1

Rails 4/5

validates :name, absence: true
pmargreff
  • 82
  • 3
  • 14