为什么我的带有 `merge` 的 ActiveRecord 作用域返回一个数组? [英] Why does my ActiveRecord scope with `merge` return an array?

查看:25
本文介绍了为什么我的带有 `merge` 的 ActiveRecord 作用域返回一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Contract 模型有一个作用域,它使用 merge 并返回一个数组,而不是我想要的 ActiveRecord::Relation.

I have a scope on my Contract model that uses merge and returns an array, not an ActiveRecord::Relation as I would like.

是的,我看到它说这是一个 ActiveRecord::Relation,但 Rails 是故意骗你的".但在这种情况下:

Yes, I've seen it said that "It is an ActiveRecord::Relation, but Rails is intentionally lying to you". But in this case:

  • 范围使用merge
  • 仅当它是链中的最后一个作用域时才有效
  • 它返回的对象表示它属于 Array
  • 它返回的对象在其祖先中没有任何关于 ActiveRecord 的内容
  • 在返回值上调用 ActiveRecord::Relation 方法(如 scoped)会引发 NoMethodError: undefined method 'scoped' for []:Array.
  • 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.

范围在 Contract 上,看起来像

The scope is on Contract and looks something like

scope :hourly, scoped.merge(Division.find_by_name!('Hourly').contracts)

为什么这会返回一个数组?我可以让它返回一个 ActiveRecord::Relation 吗?

Why is this returning an array? Can I get it to return an ActiveRecord::Relation?

推荐答案

参考以上评论.我尝试了一种虚拟关系,我希望你与部门和合同有这种关系.

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...

这篇关于为什么我的带有 `merge` 的 ActiveRecord 作用域返回一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆