Reputation: 6705
ActiveRecord offers attribute helper methods such as _?
and the "dirty" methods (_changed?
etc.)
Is there a Rails way to define these same methods on non-persisted or "virtual" attributes?
I'm hoping for something like:
class MyClass < ActiveRecord::Base
some_macro :my_attribute
end
$ @my_class = MyClass.new
$ @my_class.my_attribute? # => false
$ @my_class.my_attribute_changed? # => false
Upvotes: 2
Views: 762
Reputation: 7111
Well this was certainly something interesting to investigate. Apparently there is not a straight forward way to do this... here are two things I found
From 2011 - reinforces the 2009 post but makes it a bit cleaner. You create a module that updates the attribute hash. From the Brandon Weiss post:
# app/models/dirty_associations.rb
module DirtyAssociations
attr_accessor :dirty
def make_dirty(record)
self.dirty = true
end
def changed?
dirty || super
end
end
# app/models/lolrus.rb
class Lolrus
include DirtyAssociations
has_and_belongs_to_many :buckets,
:after_add => :make_dirty,
:after_remove => :make_dirty
end
There is also this plugin mentioned here but I am not sure how useful it is for you.
Upvotes: 1