Calculate Percent of total from scoped records and display virtual attributes (Rails / Active Record)

痴心易碎 提交于 2019-12-12 01:11:34

问题


Create a scope, maybe something like this..

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

that creates two virtual attributes, market_value and percent. The problem I am having is creating the percent with the sum() included. If I add sum(), the scope returns one record.

I need to calculate the percent of market_value relative to the total market value of the scoped record set.

example:

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

however, if I scope it to where market_value < 6, I should see

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

How can I accomplish this?

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

So far,

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

回答1:


I don't know if there's a way to do this in a single query, but we can get it in two queries:

require 'active_record'

ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'

ActiveRecord::Schema.define do
  self.verbose = false
  create_table :positions do |t|
    t.integer :quantity
    t.integer :market_price
  end
end

class Position < ActiveRecord::Base
  def self.with_market_value
    select "*, 
            quantity*market_price as market_value,
            quantity*market_price/#{total.to_f} as percent"
  end

  def self.total
    select('sum(quantity*market_price) as sum_of_market_values').first.sum_of_market_values
  end
end

Position.create! quantity: 25, market_price: 4
Position.create! quantity: 25, market_price: 4
Position.create! quantity: 25, market_price: 4
Position.create! quantity: 25, market_price: 4
Position.create! quantity: 25, market_price: 4
Position.create! quantity: 25, market_price: 20

Position.with_market_value.map { |p| [p.market_value, p.percent] }
# => [[100, 0.1], [100, 0.1], [100, 0.1], [100, 0.1], [100, 0.1], [500, 0.5]]

Position.where('market_price < 10').with_market_value.map { |p| [p.market_value, p.percent] }
# => [[100, 0.2], [100, 0.2], [100, 0.2], [100, 0.2], [100, 0.2]]

# ** NOTE THAT IT EXECUTES EAGERLY **
Position.with_market_value.where('market_price < 10').map { |p| [p.market_value, p.percent] }
# => [[100, 0.1], [100, 0.1], [100, 0.1], [100, 0.1], [100, 0.1]]


来源:https://stackoverflow.com/questions/17222379/calculate-percent-of-total-from-scoped-records-and-display-virtual-attributes-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!