I have some data inside this variable and I want to know how could I write an method to give me the sum of the items price.
Model names and their associations:
Order
- belongs_to :customer
- has_many :item_orders
- has_many :items, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true, :reject_if => lambda { |a| a['item_id'].blank? }
Item
- has_many :item_orders, :dependent => :destroy
- has_many :orders, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true
ItemOrder
- belongs_to :item
- belongs_to :order
doing:
<%= debug @order.items %>
# returns me
- !ruby/object:Item
attributes:
id: 31
title: Golden Ring 2
price: 13445.0
labour_cost: 500.0
item_type_id: 10
created_at: 2011-08-13 10:53:24.000000000Z
updated_at: 2011-08-18 06:10:36.000000000Z
photo: golden_ring.jpg
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
- !ruby/object:Item
attributes:
id: 32
title: Special Pendant
price: 171.67
labour_cost: 120.0
item_type_id: 20
created_at: 2011-08-13 11:09:43.000000000Z
updated_at: 2011-08-14 06:03:02.000000000Z
photo: prd_194_48cd9b21771dd.jpg
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
So, I want to write a method in the Order model class to make possible writes something like this on the view.
<%= @order.items.total_price %>
The total_price method will sum all the item prices and multiply by the quantity that contains in @order.items.
My doubt is: from inside the method, how could I have access to the items collection to perform the sum operation.
def total_price
self.item_order.each do |i| {
result += i.quantity * i.items.price
}
end
EDIT: I totally forgot to mention that I have to consider the quantity also to make this math.
You have two possible approaches.
1) Use ActiveRecord
sum. This is efficient as the SUM operation is performed in the DB. When you are dealing with 100s of rows this is the way to go:2) Use Enumeration
sum. Here you are operating on an existing array.I use this approach when my
has_many associationlist size is small( < 10) and already eager loaded.Edit 1: Based on additional requirement
Using ActiveRecord:
Using Enumeration