I have two models. order and 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 include the following attributes – :product_id, :size, :quantity.
It’s possible that an order can have more than one line_item for the same product and size, in which case, I want to be able to access the line_items merged into one with the quantity being the total of all of them. For example, an order might have the following line_items:
# | product_id | size | quantity
1 | 1 | small | 1
2 | 1 | small | 2
3 | 1 | medium | 1
4 | 2 | small | 1
Which should be merged to:
# | product_id | size | quantity
1 | 1 | small | 3
2 | 1 | medium | 1
3 | 2 | small | 1
It seems natural to me that this should either be a scope or a class method on the order model, so I can call @order.line_items_merged or something similar from the view, but I’m not quite sure how to implement it. Can anyone help?
Does it really make sense to have multiple line items for the same (product, size) pair? Will you actually ever use them separately, or only merged?
Personally I would consider changing the logic so that you can’t have more than one line item for the same product and size (i.e. incrementing quantity directly, rather creating multiple records to merge), and thus avoid the issue!