如何通过多对多关联获取记录?

时间:2014-06-23 20:27:27

标签: ruby-on-rails ruby activerecord

我在Rails 4应用程序中有这些模型:

class Invoice < ActiveRecord::Base

  has_many  :allocations
  has_many  :payments, :through => :allocations

end

class Allocation < ActiveRecord::Base

  belongs_to :invoice
  belongs_to :payment

end

class Payment < ActiveRecord::Base

  has_many    :allocations
  has_many    :invoices, :through => :allocations

end

如何获取与某个特定invoices X相关的所有payment

我一整天都试图绕过这一切,但无济于事。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

简单如下:

payment.invoices

这将遵循您的关联,通过分配模型。

答案 1 :(得分:1)

试试这个, 确定付款,然后确定这样的发票

payment_invoices = Payment.find(payment_id).invoices