【问题标题】:Rails 3. get attribute of related modelRails 3.获取相关模型的属性
【发布时间】:2012-06-01 22:16:34
【问题描述】:

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

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。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord join


    【解决方案1】:

    Invoice.joins(:enrollments).uniq

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多