ruby-on-rails - ActiveRecord 关系不转换为数组
问题描述
我的模型中有一个范围
class AllowanceandBenefit < ApplicationRecord
belongs_to :user
#belongs_to :salary_payroll
scope :regular_allowances, ->(month) { where(is_regular: true, month_nepali: month) }
scope :onetime_allowances, ->(month) { where(is_regular: false, month_nepali: month) }
end
我想从另一个工资模型中使用该范围
def calculate_allowances
self.total_monthly_income += AllowanceandBenefit.regular_allowances(nepali_month).amount +
AllowanceandBenefit.onetime_allowances(nepali_month).amount
end
但这不起作用,因为 AllowanceandBenefit.regular_allowances(nepali_month) 返回 ActiveRecord Relation 对象,当我尝试应用 .to_a、.to_json 等方法时,它给了我以下错误
ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block
: SELECT "allowanceand_benefits".* FROM "allowanceand_benefits" WHERE "allowanceand_benefits"."is_regular" = $1 AND "allowanceand_benefits"."month_nepali" = $2
from /home/rabin/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:611:in `async_exec_params'
我已经通过 stackoverflow 和 google 进行了搜索,但无法提出有效的解决方案。如果有人能告诉我是否有一些很好的方法可以将这两个范围合并为一个,那就太好了,这样我就不必为布尔字段的每个状态编写两个范围。提前致谢
解决方案
请尝试以下查询
AllowanceandBenefit.regular_allowances(nepali_month).or.onetime_allowances(nepali_month).sum(&:amount)
推荐阅读
- .net - MySQL服务器安装指南
- png - 如何将 PNG 文件的签名更改为“未损坏”?
- amazon-web-services - 如何使用 CloudFormation 创建具有集成 RDS 的 AWS Elasticbeanstalk 应用程序?
- c - 如何存储一个字符串数组以便以后可以引用它?
- database - How to generate sql col with binary function in DolphinDB script?
- c# - UWP - 如何在 C# 中使用 OneDrive API 同步文件
- python - Pandas:仅当时间戳大于另一列的时间戳时才获取一列的累积总和
- javascript - Button wont call a function in JavaScript?
- isabelle - Isabelle/HOL 中的 thy_goal_defn 和关键字
- javascript - React.js PWA 中桌面和移动设备的分离设计