0

スコープを作成します。おそらくこのようなものです..

scope :mv, select('*,quantity*market_price as market_value, quantity*market_price/sum(quantity*market_price) as percent')

これにより、market_value と percent という 2 つの仮想属性が作成されます。私が抱えている問題は、sum() を含めてパーセントを作成することです。sum() を追加すると、スコープは 1 つのレコードを返します。

範囲指定されたレコード セットの合計市場価値に対する market_value の割合を計算する必要があります。

例:

1, market_value: 100, percent: .10
2, market_value: 100, percent: .10
3, market_value: 100, percent: .10
4, market_value: 100, percent: .10
5, market_value: 100, percent: .10
6, market_value: 500, percent: .50
Total is 1000

ただし、market_value < 6 の範囲にスコープを設定すると、

1, market_value: 100, percent: .20
2, market_value: 100, percent: .20
3, market_value: 100, percent: .20
4, market_value: 100, percent: .20
5, market_value: 100, percent: .20
Total 500

どうすればこれを達成できますか?

self.pct メソッドを作成しましたが、self.pct メソッドの問題は、すべてのスコープの後に実行する必要があることです。再スコープされた場合、ソリューションは間違っています

ここのところ、

class Position < ActiveRecord::Base
  attr_accessible :account_id, :account_type, :market_price, :quantity, :report_date, :symbol

  scope :long_only, where(:account_type => 'L')
  scope :short_only, where(:account_type=>"S")
  scope :equity_only, :conditions => ["symbol <> 'USD'"]

 scope :mv, select('*,quantity*market_price as market_value, quantity*market_price/sum(quantity*market_price) as percent')

 scope :mv1, lambda{|total| select(total) }

  #the problem with the self.pct method is that it needs to be run after all the scopes. if rescoped, the solution is wrong

 def self.pct 
   string="*,(quantity*market_price) as market_value, (market_price*quantity/#{sum_market_value}) as percent"
   mv1(string)
 end


  def market_value
    self.market_price*self.quantity
  end


  def self.sum_market_value
    sum('quantity*market_price')
  end
end
4

1 に答える 1