ActiveRecord提供属性辅助方法,如_?
和"脏"方法(_changed?
等)
有没有一种Rails方法可以在非持久化或"虚拟"属性上定义这些相同的方法?
我希望有这样的东西:
class MyClass < ActiveRecord::Base
some_macro :my_attribute
end
$ @my_class = MyClass.new
$ @my_class.my_attribute? # => false
$ @my_class.my_attribute_changed? # => false
这当然是一个有趣的调查。显然没有一个直接的方法来做到这一点。。。这是我发现的两件
自2009年
从2011年开始——强化了2009年的帖子,但让它变得更干净了。您可以创建一个模块来更新属性哈希。来自Brandon Weiss的帖子:
# 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
这里也提到了这个插件,但我不确定它对你有多有用。