ActiveRecord关系不会转换为数组

时间:2018-12-25 03:12:25

标签: ruby-on-rails ruby-on-rails-4 activerecord ruby-on-rails-5

我的模型中有一个示波器

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,但无法提出有效的解决方案。 如果有人可以告诉我是否存在将这两个合并范围合并为一个好的方法,那么我也不必为布尔字段的每种状态编写两个合并范围,这也很好。预先感谢

2 个答案:

答案 0 :(得分:0)

请尝试以下查询

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

答案 1 :(得分:0)

在范围内传递两个参数。第二个参数可以具有true,false或同时具有[true,false]。

class AllowanceandBenefit < ApplicationRecord
  belongs_to :user
  #belongs_to :salary_payroll
  scope :onetime_regular_allowances, ->(month, is_regular) { where(is_regular: is_regular, month_nepali: month) }
end

class PayRoll < ApplicationRecord

  def calculate_allowances
    self.total_monthly_income += AllowanceandBenefit.onetime_regular_allowances(nepali_month).sum(&:amount)                                  
  end

end