views:

43

answers:

1

I have a model with a completed:boolean column that I'd like override so I can add some conditional code.

I've never override an ActiveRecord attribute before and wanted to know if the method below is good practice?

class Article < ActiveRecord::Base
  def completed=(b)
    write_attribute(:completed, b)
    # IF b is true then do something
  end
end
+2  A: 

Your approach is fine. The method you've suggested is the one described in the ActiveRecord documentation (scroll down to the heading Overwriting default accessors)

One thing I would add however, is that depending on the specifics of your circumstances you may be able to achieve what you're after using a before_save callback as an alternative.

mikej
I would use `self[:completed] = b` rather than `write_attribute`, it just feels neater.
Ryan Bigg
Yep, ActiveRecord's `[]` and `[]=` are just wrappers around `read_attribute` and `write_attribute` respectively so use whichever feels more natural to you.
mikej