问题
I have a scope on my Contract
model that uses merge
and returns an array, not an ActiveRecord::Relation
as I would like.
Yes, I've seen it said that "It is an ActiveRecord::Relation, but Rails is intentionally lying to you". But in this case:
- The scope uses
merge
- it only works if it's the last scope in the chain
- The object it returns says it's of class
Array
- The object it returns has nothing about
ActiveRecord
in its ancestors - Calling
ActiveRecord::Relation
methods likescoped
on the return value raises raisesNoMethodError: undefined method 'scoped' for []:Array
.
The scope is on Contract
and looks something like
scope :hourly, scoped.merge(Division.find_by_name!('Hourly').contracts)
Why is this returning an array? Can I get it to return an ActiveRecord::Relation
?
回答1:
Ref comments above. I gave this a go with a dummy relationship which I expect you have with Division and Contract.
# app/models/contract.rb
scope :hourly,
select: 'distinct contracts.*',
joins: :divisions,
conditions: {
"divisions.name" => 'Hourly'
},
order: :id
contracts = Contracts.hourly
# => [#<Contract id: 1>, #<Contract id: 2>]
contracts.class
# => #<ActiveRecord::Relation>
contracts.scoped.class
# => #<ActiveRecord::Relation>
contracts.arel
# => #<Arel::SelectManager:0x007fab629f7e90>
contracts.to_a
# => [#<Contract id: 1>, #<Contract id: 2>]
contracts.to_sql
# => SELECT distinct contracts.* FROM `contracts` INNER JOIN `divisions` ON `divisions`.`contract_id` = `contracts`.`id` WHERE `divisions`.`name` = 'Hourly' ORDER BY id
Let me know if this is what you were looking for...
来源:https://stackoverflow.com/questions/16927437/why-does-my-activerecord-scope-with-merge-return-an-array