首页 > 解决方案 > 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 进行了搜索,但无法提出有效的解决方案。如果有人能告诉我是否有一些很好的方法可以将这两个范围合并为一个,那就太好了,这样我就不必为布尔字段的每个状态编写两个范围。提前致谢

标签: ruby-on-railsruby-on-rails-4activerecordruby-on-rails-5

解决方案


请尝试以下查询

AllowanceandBenefit.regular_allowances(nepali_month).or.onetime_allowances(nepali_month).sum(&:amount)

推荐阅读