I have an object that inherits from ActiveRecord, yet it has an attribute that is not persisted in the DB, like:
class Foo < ActiveRecord::Base
attr_acces
ActiveRecord
has the #attribute
method (source) which once invoked from your class will let ActiveModel::Dirty
to create methods such as bar_was
, bar_changed?
, and many others.
Thus you would have to call attribute :bar
within any class that extends from ActiveRecord
(or ApplicationRecord
for most recent versions of Rails) in order to create those helper methods upon bar
.
Edit: Note that this approach should not be mixed with attr_accessor :bar
Edit 2: Another note is that unpersisted attributes defined with attribute
(eg attribute :bar, :string
) will be blown away on save. If you need attrs to hang around after save (as I did), you actually can (carefully) mix with attr_reader
, like so:
attr_reader :bar
attribute :bar, :string
def bar=(val)
super
@bar = val
end