I have the following (simplified) model and migration:
Model:
class User < ActiveRecord::Base
attr_readonly :contacted
validates :contacted, :inclusion => { :in => [true, false] }
def set_contacted
self.contacted = true
end
def unset_contacted
# self.contacted = false
self.contacted = "0"
end
end
Migration:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.boolean :contacted, :null => false, :default => false
t.timestamps
end
end
end
As you can kind of see in the comment in my model, setting the variable contact to false results in an error – I can only set it to “0”. Why? I don’t see how “false” would violate the null constraint, right?
Edit:
For clarification, I am using PostgreSQL and ActiveRecord. The error that I’m getting is this:
C:/Ruby193/lib/ruby/gems/activerecord-3.2.8/lib/active_record/validations.rb:56:in 'save!' Validation failed: ActiveRecord::RecordInvalid)
I get that error even if I remove the “validates” statement from my model, and even if I remove the NULL constraint from the migration. It’s something to do with setting the value of the attribute to be false. Is there some odd constraint on ActiveRecord booleans?
No one seems able to solve this, but it’ no longer an issue for me. My model is better served by using a state_machine gem, so I removed this field altogether.