问题描述
我有一组简单的两个相关表的订单",其中包含许多line_items".还有一个与订单项相关联的数量,例如
I hava a simple set of two related tables of an 'order' that has many 'line_items'. There is also a quantity associated to a line item, e.g.
订单1
line_item a: '初学者编织篮子',数量:3
line_item b:吸血鬼指南",数量:1
Order1
line_item a: 'basket weaving for beginners', quantity: 3
line_item b: 'a dummies guide to vampirism', quantity: 1
当我建立迁移时,我可以使用以下方法包含数量:
When I establish the migration I can include the quantity using:
Order.find(:all).each do |o|
o.update_attribute :line_items_count, o.line_items.map(&:quantity).sum
end
这给了我正确的项目数 (4),但我似乎无法在 Order 模型上做到这一点,因为我无法传递订单项的数量,所以它只是很重要订单项的数量 (2).
which gives me the correct number of items (4), but I don't appear to be able to do it on the Order model because I'm unable to pass in the quantity of line items, and so it just counts the number of line items (2).
所以在 line_item 模型中我有:
So in the line_item model I have:
belongs_to :order, :counter_cache => true
有什么办法可以指定数量,使其正确显示为 4 而不是 2?
Is there any way I can specify the quantity so that it correctly says 4 instead of 2?
推荐答案
'counter_cache` 功能旨在维护依赖项的计数(而不是总和).
The 'counter_cache` feature to meant to maintain the count(not the sum) of dependent items.
您可以通过编写几行 ruby 代码轻松实现这一点.
You can easily achieve this by writing few lines of ruby code.
让我们假设您的 orders
表中有一个名为 line_items_sum
的列.此列的值应默认为 0.
Let us assume that you have a column called line_items_sum
in your orders
table. The value of this column should default to 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
类.
Now add the callback to the LineItem
class.
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
这篇关于:counter_cache 总项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!