0

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?

Bryce
  • 2,802
  • 1
  • 21
  • 46
  • What database system are you using? Also, please add the error message to your question. –  Nov 30 '12 at 08:40
  • I'm using Postgresql. I get a whole string of messages basically saying that ActiveRecord "save!" failed. – Bryce Nov 30 '12 at 09:02
  • 1
    Even if you don't think it'll help, it's always a good idea to paste your error message into the question. –  Nov 30 '12 at 09:37

2 Answers2

1

It's a bit difficult answering your question without having the specific error information.

First I'd change attr_readonly to attr_accessible - So the field will be updatable.

Secondly, I'd re-write your method:

  def unset_contacted
    self.contacted = false
    self.save! # Saving your methods (the ! is for throwing an exception if it fails).
  end
hrr
  • 1,676
  • 1
  • 13
  • 15
0

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.

Bryce
  • 2,802
  • 1
  • 21
  • 46