开发者

Ruby 1.9.2 / Rails 3 - Summation from a hash collection

开发者 https://www.devze.com 2023-02-09 13:45 出处:网络
I\'m having some difficulties creating a sum from values I have in a collection. The collection I have is from (in rails) a one to many relationship, an order has many products.

I'm having some difficulties creating a sum from values I have in a collection. The collection I have is from (in rails) a one to many relationship, an order has many products.

The products are hashes and have a price: value.

I've used the built in array.sum method before, so I was trying to grab all the prices from my products, and create a new array, and sum that, but have been unable t开发者_Go百科o select just the price values from my products for this array.

Is there a better way I should be attempting to do this? I'm trying to build a method for my Order model that defines the order's total price from taking the sum of the product prices that belong to the order.


I would do the following:

class Order
  has_many :products

  def price
    products.all.sum(&:price)
  end
end

Now calling .price on an Order object will sum all product prices for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消