jspooner
jspooner

Reputation: 11315

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 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

Upvotes: 3

Views: 3465

Answers (1)

mikej
mikej

Reputation: 66263

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.

Upvotes: 3

Related Questions