Rails 将除法计算添加到现有查询

Posted

技术标签:

【中文标题】Rails 将除法计算添加到现有查询【英文标题】:Rails add divide calculation to existing query 【发布时间】:2021-10-19 19:51:11 【问题描述】:

我有一个查询,我在其中提取了所有投资于投资组合的用户,如下所示:

class PortfolioshareholdersQuery
  def initialize(portfolio)
    @portfolio = portfolio
  end

  def call
    User.joins(:cash_transactions)
        .where(cash_transactions:  to_wallet: portfolio.wallet )
        .select('users.*, SUM(cash_transactions.shares_number) as total_shares_number')
        .group('users.id')
  end

  attr_reader :portfolio
end

是否可以在上面的查询中添加一行来将两个数字相除,如下所示?

(user.total_shares_number / portfolio.portfolio_setup_infos.last.total_shares_sold)

# total_shares_number comes from first select
# portfolio_setup_infos is a has_many relation to portfolio

[编辑]

#models association
class User < ApplicationRecord
  has_one  :wallet, as: :walletable
  has_many :cash_transactions, through: :wallet
end

class Portfolio < ApplicationRecord
  has_one  :wallet, as: :walletable
end

class Wallet < ApplicationRecord
  belongs_to :walletable, polymorphic: true

  has_many   :cash_transactions
end

class CashTransaction < ApplicationRecord
  belongs_to :wallet
  belongs_to :to_wallet, class_name: 'Wallet', optional: true
end

[编辑 2]

> divisor = portfolio.portfolio_setup_infos.last.total_shares_sold
  PortfolioSetupInfo Load (0.5ms)  SELECT "portfolio_setup_infos".* FROM "portfolio_setup_infos" WHERE "portfolio_setup_infos"."portfolio_id" = $1 ORDER BY "portfolio_setup_infos"."id" DESC LIMIT $2  [["portfolio_id", 6], ["LIMIT", 1]]
 => 263

> shareholders = User.joins(:cash_transactions).where(cash_transactions:  to_wallet: portfolio.wallet ).select("users.*, SUM(cash_transactions.shares_number) as total_shares_number, (total_shares_number/#divisor").group('users.id')
  Wallet Load (0.6ms)  SELECT "wallets".* FROM "wallets" INNER JOIN "spv_setups" ON "wallets"."walletable_id" = "spv_setups"."id" WHERE "spv_setups"."portfolio_id" = $1 AND "wallets"."walletable_type" = $2 LIMIT $3  [["portfolio_id", 6], ["walletable_type", "SpvSetup"], ["LIMIT", 1]]
  User Load (3.3ms)  SELECT users.*, SUM(cash_transactions.shares_number) as total_shares_number, (total_shares_number/263 FROM "users" INNER JOIN "wallets" ON "wallets"."walletable_type" = $1 AND "wallets"."walletable_id" = "users"."id" INNER JOIN "cash_transactions" ON "cash_transactions"."wallet_id" = "wallets"."id" WHERE "cash_transactions"."to_wallet_id" = $2 GROUP BY "users"."id" /* loading for inspect */ LIMIT $3  [["walletable_type", "User"], ["to_wallet_id", 8], ["LIMIT", 11]]
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR:  syntax error at or near "FROM")
LINE 1: ... as total_shares_number, (total_shares_number/263 FROM "user...
                                                         ^

【问题讨论】:

用户模型和投资组合模型之间的关系是什么? @LesNightingill 这两个模型之间没有明确的关系。已更新问题以显示关系。 您所需计算的分母来自投资组合的一个实例(投资组合)。指定在此计算中使用哪个 Portfolio 实例的条件是什么? 投资组合在类调用中传递 - PortfolioShareholdersQuery.new(portfolio).call 【参考方案1】:
class Portfolio < ApplicationRecord
  def divisor
    portfolio_setup_infos.last.total_shares_sold
  end
end

class PortfolioShareholdersQuery
  def initialize(portfolio)
    @portfolio = portfolio
    @divisor = portfolio.divisor.to_f
  end

  def call
    select =<<-SEL.squish
                 users.*,
                 SUM(cash_transactions.shares_number) as total_shares_number,
                 (SUM(cash_transactions.shares_number)/#divisor) as ratio
              SEL

    User.joins(:cash_transactions)
        .where(cash_transactions:  to_wallet: portfolio.wallet )
        .select(select)
        .group('users.id')
  end

  attr_reader :portfolio, :divisor
end

【讨论】:

我收到ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "FROM") LINE 1: ... as total_shares_number, (total_shares_number/263 FROM "user... 我添加了一个别名,这可能是问题所在。你用的是什么数据库?后格雷斯? mysql?如果仍然失败,请向我们展示整个 sql 查询和错误消息。 我正在使用 Postgres。我在控制台中对其进行了测试,好吧,那里没有更多的错误行 - 我已经更新了问题。 您应该能够在调用查询时在控制台中看到实际的 sql,或者通过附加 .to_sql 然后 #call 方法将返回 sql 查询。你得到了什么? 我相信我最后一次编辑我的问题(我在那里发布了一个错误)回答了你的问题

以上是关于Rails 将除法计算添加到现有查询的主要内容,如果未能解决你的问题,请参考以下文章

Win32 应用程序的除法按钮

添加,减法,除法和乘以存储在布尔数组中的两个二进制数

sql 查询出的结果进行除法运算,结果无法四舍五入。求助!

018Java中除法的是用,解决除法计算精度问题

计算机原理 3.6 定点数除法

Excel怎么进行乘法和除法