开发者

Overriding an ActiveRecord attribute

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 A开发者_开发问答ctiveRecord 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜