【发布时间】:2011-08-19 03:19:48
【问题描述】:
我在这个变量中有一些数据,我想知道如何编写一个方法来给我商品价格的总和。
模型名称及其关联:
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
在做:
<%= 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
所以,我想在 Order 模型类中编写一个方法,以便在视图上写入类似这样的内容。
<%= @order.items.total_price %>
total_price 方法将对所有商品价格求和并乘以 @order.items 中包含的数量。
我的疑问是:从方法内部,我怎么能访问items 集合来执行求和操作。
def total_price
self.item_order.each do |i| {
result += i.quantity * i.items.price
}
end
编辑:我完全忘了提到我还必须考虑数量才能做出这个数学。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3