使用`select`子句以及`includes`和`references`

时间:2014-08-21 20:14:00

标签: ruby-on-rails ruby-on-rails-4

我有两种模式:

class Order <  < ActiveRecord::Base
  # id
  # total
  # customer_id
  # custom_field1
  # custom_field2
  # custom_field3
  # custom_field4

  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :order
end

我想查询特定客户的订单项,并急切加载每个订单项的order。我不想在急切加载时在order模型中包含自定义字段。

我尝试使用以下查询:

LineItem.
  includes(:order).
  references(:order).
  where(customer_id: 2).
  select("line_items.*, orders.id, orders.total, orders.customer_id")

Rails生成的SQL包含LineItemOrder和明确select ed列的所有列。

如何限制使用includes + references时返回的列集?

1 个答案:

答案 0 :(得分:1)

我认为您可以使用pluck代替:

LineItem.
  includes(:order).
  references(:order).
  where(customer_id: 2).
  pluck(#the attributes you need here)

http://apidock.com/rails/ActiveRecord/Calculations/pluck