我的Contract
模型上的范围使用merge
并返回一个数组,而不是我想要的ActiveRecord::Relation
。
是的,我见过它说"It is an ActiveRecord::Relation, but Rails is intentionally lying to you"。但在这种情况下:
merge
Array
ActiveRecord
ActiveRecord::Relation
等scoped
方法会引发加注NoMethodError: undefined method 'scoped' for []:Array
。范围在Contract
上,看起来像
scope :hourly, scoped.merge(Division.find_by_name!('Hourly').contracts)
为什么这会返回一个数组?我可以让它返回ActiveRecord::Relation
吗?
答案 0 :(得分:1)
上面的评论。我给了这个虚拟关系,我希望你有分部和合同。
# 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
请告诉我这是否是你要找的......