有没有一种简单的方法来计算Rails中的sumproduct?

时间:2020-03-22 07:32:38

标签: ruby-on-rails ruby-on-rails-5

我有一个PositionGroup的{​​{1}}。

每当触摸has_many :positions对象时,我都想像这样更新position_group

pg.average_price

在我的回调方法中,我尝试了以下方法:

# Average Price = ((position1.transaction_price * (position1.volume/total_volume) + 
# position2.transaction_price * (position2.volume/total_volme)) 

但是当存在多个 def update_average_price total_volume = positions.sum(:volume) avg_price = positions.sum("transaction_price * (volume/#{total_volume})") update_column(:average_price, avg_price) end 时我检查avg_price的值时,我得到的是positions

这是我针对此特定功能的规范:

0.0

这是我运行它时的结果:

it "should calculate the Weighted Average Purchase Price of all positions" do
  # Position 3: Price = 20, volume = 200
  # (Position 1 Price * (Position 1 Units/Total # of Units)) +
  # (Position 2 Price * (Position 2 Units/Total # of Units)) +
  # (Position 3 Price * (Position 3 Units/Total # of Units))
  # ($10 * (100/400)) + ($15 * (100/400) + $20 * (100/400)) =
  # ($2.50 + $3.75 + $5) = $11.25
  price3 = 20
  pos3 = create(:position, stock: stock, portfolio: portfolio, transaction_price: 20, current_price: price3, action: :buy, volume: 200, position_group: pg)
  expect(pg.average_price).to eql 11.25
end

我很确定问题出在这行,是从1) PositionGroup methods should calculate the Weighted Average Purchase Price of all positions Failure/Error: expect(pg.average_price).to eql 11.25 expected: 11.25 got: 0.0 (compared using eql?) 上的回调方法update_average_price开始的:

PositionGroup

是否有更好的方法来解决这个问题?或者是否有其他方法可以让我avg_price = positions.sum("transaction_price * (volume/#{total_volume})") 离开我?

1 个答案:

答案 0 :(得分:2)

avg_price = positions.sum("transaction_price * (volume/#{total_volume.to_f})")

to_f丢失,转换为float以获取小数。

示例

irb(main):022:0> Position.all
  Position Load (0.3ms)  SELECT "positions".* FROM "positions" LIMIT ?  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Position id: 1, transaction_price: 0.5e2, volume: 150, position_group_id: 1>, #<Position id: 2, transaction_price: 0.1e1, volume: 50, position_group_id: 1>]>
irb(main):023:0> Position.all.sum("transaction_price * (volume/#{total_volume.to_f})")
   (0.2ms)  SELECT SUM(transaction_price * (volume/200.0)) FROM "positions"
=> 37.75