:counter_cache为总项目

我有一个简单的两个相关的“订单”表,它有许多“line_items”。 还有与订单项相关联的数量,例如

Order1
line_item a:’为初学者编织篮子’,数​​量:3
line_item b:’吸血鬼的假人指南’,数量:1

当我建立迁移时,我可以使用以下内容包括数量:

Order.find(:all).each do |o| o.update_attribute :line_items_count, o.line_items.map(&:quantity).sum end 

这给了我正确数量的项目(4),但我似乎无法在订单模型上执行,因为我无法传递订单项的数量,因此它只计算数量订单项(2)。

所以在line_item模型中我有:

 belongs_to :order, :counter_cache => true 

有没有什么方法可以指定数量,以便正确地说4而不是2?

‘counter_cache`function旨在维护依赖项的计数(而不是总和)。

您可以通过编写几行ruby代码轻松实现此目的。

我们假设您的orders表中有一个名为line_items_sum的列。 此列的值应默认为0。

 class AddLineItemsSumToOrder < ActiveRecord::Migration def self.up add_column :orders, :line_items_sum, :integer, :default => 0 end def self.down remove_column :orders, :line_items_sum end end class Order < ActiveRecord::Base has_many :line_items end 

现在将回调添加到LineItem类。

 class LineItem < ActiveRecord::Base validates_numericality_of :quantity belongs_to :order after_save :update_line_items_sum private def update_line_items_sum return true unless quantity_changed? Order.update_counters order.id, :line_items_sum => (quantity - (quantity_was || 0)) return true end end 

我认为你最好的选择就是编写自己的方法来缓存总量。 如果您没有按照“Rails方式”来保留计数器,那么最好自己编写。