Why does my ActiveRecord scope with `merge` return an array?

不羁的心 提交于 2019-12-10 15:35:48

问题


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 like scoped on the return value raises raises NoMethodError: 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!