1

我有两个模型:注册和发票。

enrollment belongs to invoice
invoice has many enrollments

所以我有这个查询:@enrollments = Enrollment.where('invoice_id IS NOT NULL')获取属于发票的所有注册。

但我需要进行某种类型的加入,因为我真正想要的是与注册相关的发票(id、invoice_number 和总计)。

我怎样才能做到这一点?

到目前为止我在控制台中尝试过的......

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。

4

1 回答 1

4

Invoice.joins(:enrollments).uniq

于 2012-06-01T22:23:33.367 回答