2010-06-25 35 views
0

我需要一種方法來使關聯收集方法(特別是追加< <)。這裏有一個例子:如何使私人ActiveRecord的關聯收集方法

class Foo < ActiveRecord::Base 
    has_many :bars 

    def add_bar (bar) 
    # does something extra first 
    # but still also use the <<, ultimately 
    bars.send(:<<, bar) 
    end 
end 

基本上,我不想使用< <自身應用程序的任何一部分,我需要它要經過「add_bar」的方法。有什麼建議麼?

非常感謝!

回答

2

還有private_class_method(不知道我自己:))。你可以嘗試沿線

class Foo < ActiveRecord::Base 
    has_many :bars do 
    private_class_method :<< 
    end 

    def add_bar (bar) 
    # does something extra first 
    # but still also use the <<, ultimately 
    bars.send(:<<, bar) 
    end 
end 

沒有測試,看看它是否工作。

+0

感謝您的回覆!這似乎並不奏效。我得到了一個「未定義的方法'''類'模塊'」錯誤。我也嘗試過「private:<<」並得到相同的錯誤。謝謝您的幫助! – janechii 2010-06-28 15:14:16

1

創建一個位於關聯前的代理類,並將原始關聯設爲私有。這裏有一個例子:

class Foo < ActiveRecord::Base 

    has_many :_bars, :class_name => "Bar" 
    private :_weeks 

    class BarsProxy 

    include ::Enumerable 

    def initialize(weeks) 
     @weeks = weeks 
    end 

    def each 
     yield @weeks.each 
    end 

    def create(args = {}) 
     @weeks.create(args) 
    end 

    # Plus whatever other methods you want to use on the collection. 

    end 

    def weeks 
    @weeks ||= WeeksProxy.new(_weeks) 
    end 

end