2012-03-06 76 views
2

ActiveRecord的报价属性的辅助方法,如_?和“脏”的方法(_changed?等)如何将ActiveRecord属性帮助器方法添加到虚拟属性?

有一个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 

回答

1

嗯,这肯定是一些有趣的事情进行调查。显然没有做到这一点的直线前进的方向......这里有两件事情,我发现

From 2009

From 2011 - reinforces the 2009 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 

也有这个插件mentioned here,但我不知道它是怎么有用。

+0

谢谢@ScottJShea - 很遗憾地看到,虽然没有本地支持...... :( – bodacious 2012-03-07 07:39:09