Reputation: 778
I have a scope in my model
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
And I want to use that scope from another payroll model where the method is
def calculate_allowances
self.total_monthly_income += AllowanceandBenefit.regular_allowances(nepali_month).amount +
AllowanceandBenefit.onetime_allowances(nepali_month).amount
end
But this does not work because AllowanceandBenefit.regular_allowances(nepali_month) returns ActiveRecord Relation object and it is giving me following errors when I tried applying methods like .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'
I have searched through stackoverflow and google but could not come up with the solution that works. Also it would be nice if someone could tell me if there is some nice way to merge those two scopes into one so I wont have to write two scopes for each state of boolean field. Thanks in advance
Upvotes: 0
Views: 262
Reputation: 1060
Pass two argument in the scope. Second argument can have true, false, or both [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
Upvotes: 0
Reputation: 7361
Please try below query
AllowanceandBenefit.regular_allowances(nepali_month).or.onetime_allowances(nepali_month).sum(&:amount)
Upvotes: 1