0

我有一个模型(LineItem),它是另一个(发票)的孩子。在 LineItem 中,我委托了一个引用 Invoice 中的属性的方法。每当运行此方法时,它总是会运行几个 SQL 查询……就好像它在重新搜索 Invoice

模型“发票”
- 包含属性“created_at”
- 包含default_scope includes(:line_items, :payments, :sales_person)

模型“LineItem”
- 包含delegate :created_at, :to => :invoice, :prefix => true
- 另一个方法包含:

@tax_rate ||= (category.to_sym == :books ? invoice_created_at.federal_tax_rate : invoice_created_at.tax_rate)

正是在这种方法中生成了以下内容(使用“mini-profiler”gem):

SELECT `invoices`.* FROM `invoices`  WHERE `invoices`.`id` = 4 LIMIT 1
SELECT `line_items`.* FROM `line_items`  WHERE `line_items`.`invoice_id` IN (4)
SELECT `items`.* FROM `items`  WHERE `items`.`id` IN (31, 15)
SELECT `categories`.* FROM `categories`  WHERE `categories`.`id` IN (6, 1) ORDER BY name
SELECT `payments`.* FROM `payments`  WHERE `payments`.`invoice_id` IN (4)
SELECT `payment_types`.* FROM `payment_types`  WHERE `payment_types`.`id` IN (1) ORDER BY name
SELECT `sales_people`.* FROM `sales_people`  WHERE `sales_people`.`id` IN (1) ORDER BY name

它对每个行项目执行此操作。在调用 invoice_created_at.*tax_rate 方法之前,所有这些 SELECT 语句已经批量发生......

SELECT `invoices`.* FROM `invoices`  WHERE (created_at between '2011-05-01 04:00:00' and '2013-02-06 04:59:59')
SELECT `line_items`.* FROM `line_items`  WHERE `line_items`.`invoice_id` IN (4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)

我能做些什么来确保不必运行所有这些 SELECT 查询?

4

1 回答 1

0

首先,您可以停止使用default_scope includes- 典型情况不需要它,您的情况也可能不需要。

其次,更重要的是,您应该:inverse_of在关联中声明该属性,以尽量减少重新加载已在内存中的对象:

class Invoice < ActiveRecord::Base
  has_many :line_items, :inverse_of => :invoice
end

class LineItem < ActiveRecord::Base
  belongs_to :invoice, :inverse_of => :line_items
end
于 2013-02-06T03:36:14.790 回答