开发者

Overriding an ActiveRecord attribute

开发者 https://www.devze.com 2022-12-31 03:41 出处:网络
I have a model with a completed:boolean column that I\'d like override so I can add some conditional code.

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

精彩评论

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

关注公众号