如何将方法添加到has_many集合中

Cam*_*ike 1 ruby-on-rails

假设有一个典型的has_many关联

class Customer < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :customer
end
Run Code Online (Sandbox Code Playgroud)

如何在订单集合中添加方法?为了代码组织,我试图在我的Customer类中反应这个方法(这是一个简单的例子):

def update_orders
  ThirdPartyAPI.look_up(self.orders) do |order|
    # Do stuff to the orders
    # May need to access 'self', the Customer...
  end
end
Run Code Online (Sandbox Code Playgroud)

我不喜欢这个,因为它在Order课堂上讲了很多关于班级的知识Customer.我无法使用订单中的实例方法,因为ThirdPartyAPI可以对多个订单执行批量查找.我可以创建一个静态方法Order并传递订单数组和他们的父客户,但这感觉很笨重.

我在rails docs中找到了这个,但是我找不到任何在实践中如何使用它的好例子.还有其他方法吗?

den*_*iss 6

我认为应该这样做

has_many :entities do
  def custom_function here

  end

  def custom_function here

  end 
end
Run Code Online (Sandbox Code Playgroud)