【发布时间】:2011-08-31 03:44:04
【问题描述】:
我有两个模型。订单和line_item。
class Order < ActiveRecord::Base
has_many :line_items
has_many :products, :through => :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
line_items 包括以下属性 - :product_id、:size、:quantity。
对于相同的产品和尺寸,一个订单可能有多个 line_item,在这种情况下,我希望能够访问合并为一个的 line_items,其数量是所有这些的总和。例如,一个订单可能有以下 line_items:
# | product_id | size | quantity
1 | 1 | small | 1
2 | 1 | small | 2
3 | 1 | medium | 1
4 | 2 | small | 1
应该合并到:
# | product_id | size | quantity
1 | 1 | small | 3
2 | 1 | medium | 1
3 | 2 | small | 1
在我看来,这应该是订单模型上的范围或类方法,所以我可以从视图中调用@order.line_items_merged 或类似的东西,但我不太确定如何实现它。有人可以帮忙吗?
【问题讨论】:
标签: ruby-on-rails ruby