Type cast an ActiveRecord model virtual attribute

Viewed 8442

I have a model with some attributes and a virtual attribute. This virtual attribute is used to make a checkbox in the creation form.

class Thing < ActiveRecord::Base
  attr_accessor :foo
  attr_accessible :foo
end

Since the field is a checkbox in the form, the foo attribute will receive '0' or '1' as value. I would like it to be a boolean because of the following code:

class Thing < ActiveRecord::Base
  attr_accessor :foo
  attr_accessible :foo

  before_validation :set_default_bar

  private

  def set_default_bar
    self.bar = 'Hello' if foo
  end
end

The problem here is that the condition will be true even when foo is '0'. I would like to use the ActiveRecord type casting mechanism but the only I found to do it is the following:

class Thing < ActiveRecord::Base
  attr_reader :foo
  attr_accessible :foo

  before_validation :set_default_bar

  def foo=(value)
    @foo = ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value)
  end


  private

  def set_default_bar
    self.bar = 'Hello' if foo
  end
end

But I feel dirty doing it that way. Is there a better alternative without re-writing the conversion method ?

Thanks

4 Answers
Related