本文介绍了如何将ActiveRecord :: Relation添加到Rails的模型中,为什么每个模型都有单独的Relation类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Rails模型: class Project< ActiveRecord :: Base

Suppose I have a Rails model: class Project < ActiveRecord::Base

在Rails控制台中:

In the Rails console:

> Project.all
=> #<ActiveRecord::Relation []>

这似乎很合理。但是,

> Project.all.class
=> Project::ActiveRecord_Relation

是什么 项目: :ActiveRecord_Relation ?具体来说,


  • 它是如何添加(命名为)模型类的?

  • 它如何正确响应 is_a? Project.all.is_a?(ActiveRecord :: Relation)返回 true (应该是),但 Project :: ActiveRecord_Relation 实际上是 ActiveRecord :: Relation 的实例,还是其他东西?

  • 为什么这样做?为什么 Project.all 不返回 ActiveRecord :: Relation ,而不是返回 Project: :ActiveRecord_Relation

  • How did it get "added" (namespaced into) to my model class?
  • How does it respond to is_a? correctly? Project.all.is_a?(ActiveRecord::Relation) returns true (which is expected), but is Project::ActiveRecord_Relation actually an instance of ActiveRecord::Relation, or is it something else?
  • Why do this? Why doesn't Project.all return an ActiveRecord::Relation, rather than Project::ActiveRecord_Relation?

(这是在Rails 5.1的上下文中,如果它是在较旧的版本或

(This is in the context of Rails 5.1, in case it's changed in older or newer versions.)

(如果有人可以为此问题提供更好的标题,我可以进行标题编辑)

(I'm open to title edits if someone else can come up with a better title for this question)

推荐答案

实际上您要问两个问题:

There are actually two questions you are asking:


  1. 如何执行工作?

  2. 为什么会这样? (什么用?)

@arieljuod 已经给了您一些解释,并且

@arieljuod has already given you some explanations and a link.

但是第二个问题仍未得到答案。

However the second question is still unanswered.

我希望还有另一个类似的问题将帮助您找到所有答案:

There is another similar question exists which I hope will help you find all the answers:

它看起来像两个问题(通过链接和你们彼此回答)

It looks like the two questions (by the link and yours one) answer each other )

看看 @ nikita-shilnikov 的答案。祝您调查顺利!

Take a look at @nikita-shilnikov's answer. Good luck in your investigation!

这篇关于如何将ActiveRecord :: Relation添加到Rails的模型中,为什么每个模型都有单独的Relation类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 01:29