【问题标题】:ActiveRecord relation does not convert to arrayActiveRecord 关系不转换为数组
【发布时间】:2018-12-25 03:12:24
【问题描述】:

我的模型中有一个作用域

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(&amp;:amount)

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


【解决方案1】:

请尝试以下查询

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

【讨论】:

  • ArgumentError: 参数数量错误(给定 0,预期为 1)
【解决方案2】:

在范围内传递两个参数。第二个参数可以有 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2018-10-04
    • 2021-12-08
    相关资源
    最近更新 更多