0

鉴于以下情况:

class Item < ActiveRecord::Base
  has_many :order_items
  has_many :orders, through: :order_items

  attr_accessible :rent_price, :sale_price
end

class Order < ActiveRecord::Base
  has_many :order_items, dependent: :destroy

  def total
    order_items.map(&:price).reduce(:+)
  end
end

class OrderItem < ActiveRecord::Base
  belongs_to :item
  belongs_to :order

  attr_accessible :type, :quantity

  def item_price
    item.send("#{type}_price")
  end

  def price
    quantity * item_price
  end
end

Order#order_items 和 Order#total 产生 sql 查询:

irb(main):055:0> o = Order.last
  订单加载 (0.4ms) SELECT "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT 1
=> #, balance: #, notes: nil, shipping_method: nil, shipping_details: nil, created_at: "2012-09-16 17:27:39", updated_at: "2012-09-16 21:09:56">

irb(main):056:0> oi = o.order_items.includes(item::photos)
  OrderItem Load (0.4ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = 143
  项目加载(0.2 毫秒)选择“项目”。* FROM “项目” WHERE “项目”。“id” IN (227)
  照片加载(0.1ms)选择“照片”。*从“照片”WHERE“照片”。“item_id”IN(227)
=> [#,数量:1,大小:95,类型:“租”,starts_on:“2012-09-17”,ends_on:“2012-09-18”,created_at:“2012-09-16 20:03 :33", updated_at: "2012-09-16 21:09:56">]

irb(main):057:0> o.order_items
  OrderItem Load (0.4ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = 143
=> [#,数量:1,大小:95,类型:“租”,starts_on:“2012-09-17”,ends_on:“2012-09-18”,created_at:“2012-09-16 20:03 :33", updated_at: "2012-09-16 21:09:56">]

irb(main):058:0> o.total
  项目加载 (0.4ms) SELECT "items".* FROM "items" WHERE "items"."id" = 227 LIMIT 1
=> #

应该怎么做才能摆脱多余的 sql 查询?

4

1 回答 1

0

oi = o.order_items.includes(item: :photos)不会改变 o.order_items,向其中添加包含:它返回一个新的对象数组,其中应用了额外的选项。

使用o = Order.includes(order_items: {item: photos}).lastthen o.order_items 不会执行任何查询

于 2012-09-17T14:19:52.667 回答