我有两种型号:登记和发票。

enrollment belongs to invoice
invoice has many enrollments

所以我有一个查询:@enrollments = Enrollment.where('invoice_id IS NOT NULL')以获取属于发票的所有注册。
但是我需要进行某种类型的连接,因为我真正想要的是与注册相关联的发票(id、发票号和总数)。
我该怎么做?
我到目前为止在控制台上所做的尝试。。。
enrollments = Enrollment.where('invoice_id IS NOT NULL').joins(:invoice)
enrollments.each do |enrollment|
  puts enrollment.invoice_number
end

我得到NoMethodError: undefined method invoice_number for #<Enrollment:0x00000006a1e1a8>是因为我只能访问发票的id。

最佳答案

Invoice.joins(:enrollments).uniq

09-18 21:07