您需要使用订单集合并根据您自己的逻辑相应地缩小范围。尽管您当然“可以”将 order_id 直接添加到付款中,但这将使您的数据(作为缓存)非规范化,仅在您开始遇到查询中的性能瓶颈时才建议这样做 - 否则它会在数据完整性方面遇到麻烦:
class Payment < ActiveRecord::Base
has_many :line_item_payments
has_many :line_items, :through => :line_item_payments
has_many :orders, :through => :line_items
# use this to get the order quickly
def order
orders.first
end
# use this to narrow the scope on the query interface for additional modifications
def single_order
orders.limit(1)
end
end
class LineItemPayment < ActiveRecord::Base
belongs_to :line_item
belongs_to :payment
end
class LineItem < ActiveRecord::Base
belongs_to :order
has_many :line_item_payments
end