views:

46

answers:

1

I've created a simple Project model with four attributes:

Project name:string description:text complete:boolean user_id:integer

Then added some validation to the model:

class Project < ActiveRecord::Base
  validates_presence_of :name, :description, :complete
end

Now, when I attempt to save a Project in irb, I am not allowed:

>> r = Project.new(:name => 'Name', :description => 'Description', :complete => false)
=> #<Project id: nil, name: "Name", description: "Description", created_at: nil, updated_at: nil, complete: false, user_id: nil>
>> r.save
=> false

It seems like I have met all the validation requirements, yes? If I change the complete attribute to true, then I am able to save the object:

>> r.complete = true
=> true
>> r.save
=> true

I can't see what's happening here. Does the complete attribute have special meaning in a Rails project?

+1  A: 

It has more to do with validates_presence_of and the boolean value, which blocks a save call if any of the named attributes returns true to the blank? method.

"".blank? => true
[].blank? => true
false.blank? => true
nil.blank? => true

You'll have to use another validation to check for completeness such as:

class Project < ActiveRecord::Base
  validates_presence_of :name, :description
  validates_inclusion_of :complete, :in => [true, false]
end
EmFi
That did the trick, thanks. I might see that as a bug if I was feeling pessimistic :)
huntca
It's not a bug, it's a feature.
EmFi