本文介绍了将对象数组转换为 ActiveRecord::Relation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我们称之为Indicator.我想在这个数组上运行 Indicator 类方法(那些 def self.subjects 品种、范围等).我知道在一组对象上运行类方法的唯一方法是让它们成为 ActiveRecord::Relation.所以我最终求助于向 Array 添加一个 to_indicators 方法.

I have an array of objects, let's call it an Indicator. I want to run Indicator class methods (those of the def self.subjects variety, scopes, etc) on this array. The only way I know to run class methods on a group of objects is to have them be an ActiveRecord::Relation. So I end up resorting to adding a to_indicators method to Array.

def to_indicators
  # TODO: Make this less terrible.
  Indicator.where id: self.pluck(:id)
end

有时我会在类方法中链接很多这样的作用域来过滤结果.因此,即使我在 ActiveRecord::Relation 上调用了一个方法,我也不知道如何访问该对象.我只能通过all获取其中的内容.但是 all 是一个数组.那么我必须将该数组转换为 ActiveRecord::Relation.例如,这是其中一种方法的一部分:

At times I chain quite a few of these scopes to filter down the results, within the class methods. So, even though I call a method on an ActiveRecord::Relation, I don't know how to access that object. I can only get to the contents of it through all. But all is an Array. So then I have to convert that array to a ActiveRecord::Relation. For example, this is part of one of the methods:

all.to_indicators.applicable_for_bank(id).each do |indicator|
  total += indicator.residual_risk_for(id)
  indicator_count += 1 if indicator.completed_by?(id)
end

我想这可以归结为两个问题.

I guess this condenses down to two questions.

  1. 如何将对象数组转换为 ActiveRecord::Relation?最好不要每次都执行 where.
  2. 在 ActiveRecord::Relation 上运行 def self.subjects 类型方法时,如何访问该 ActiveRecord::Relation 对象本身?
  1. How can I convert an Array of objects to an ActiveRecord::Relation? Preferably without doing a where each time.
  2. When running a def self.subjects type method on an ActiveRecord::Relation, how do I access that ActiveRecord::Relation object itself?

谢谢.如果我需要澄清任何事情,请告诉我.

Thanks. If I need to clarify anything, let me know.

推荐答案

您不能将数组转换为 ActiveRecord::Relation,因为 Relation 只是 SQL 查询的构建器,其方法不对实际数据进行操作.

You cannot convert an Array to an ActiveRecord::Relation since a Relation is just a builder for a SQL query and its methods do not operate on actual data.

但是,如果您想要的是关系,那么:

However, if what you want is a relation then:

  • 对于 ActiveRecord 3.x,不要调用 all 而是调用 scoped,它将返回一个 Relation,它表示 all 会给你一个数组.

  • for ActiveRecord 3.x, don’t call all and instead call scoped, which will give back a Relation which represents the same records that all would give you in an Array.

对于 ActiveRecord 4.x,只需调用 all,返回一个 Relation.

for ActiveRecord 4.x, simply call all, which returns a Relation.

在 ActiveRecord::Relation 上运行 def self.subjects 类型方法时,我如何访问该 ActiveRecord::Relation 对象本身?

当在 Relation 对象上调用该方法时,self 是关系(相对于它在其中定义的模型类).

When the method is called on a Relation object, self is the relation (as opposed to the model class it’s defined in).

这篇关于将对象数组转换为 ActiveRecord::Relation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:45