ActiveRecord::Relation 对象如何调用类方法 [英] How can an ActiveRecord::Relation object call class methods

查看:27
本文介绍了ActiveRecord::Relation 对象如何调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ActiveRecord::Relation 对象如何调用类方法?

How can an ActiveRecord::Relation object call class methods?

class Project < ActiveRecord::Base
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project

  def self.initial_tasks # class methods
   # here return initial tasks
  end
end

现在我们可以调用:

Project.first.tasks.initial_tasks # how it works

initial_tasks 是一个类方法,我们不能在对象上调用类方法.

initial_tasks is a class method and we can't call class methods on an object.

Project.first.tasks 返回一个 ActiveRecord::Relation 对象,那么它怎么能调用initial_tasks?

Project.first.tasks returns an ActiveRecord::Relation object, so how could it be able to call initial_tasks?

请解释.

推荐答案

关于 ActiveRecord::Relation 对象的类方法的应用程序的文档并不多,但我们可以通过以下方式理解这种行为看看 ActiveRecord 范围 是如何工作的.

There's not much documentation on the application on class methods to ActiveRecord::Relation objects, but we can understand this behavior by taking a look at how ActiveRecord scopes work.

首先,Rails 模型范围将返回一个 ActiveRecord::Relation 对象.来自文档:

First, a Rails model scope will return an ActiveRecord::Relation object. From the docs:

模型上的类方法在作用域上自动可用.假设以下设置:

Class methods on your model are automatically available on scopes. Assuming the following setup:

class Article < ActiveRecord::Base
  scope :published, -> { where(published: true) }
  scope :featured, -> { where(featured: true) }

  def self.latest_article
    order('published_at desc').first
  end

  def self.titles
    pluck(:title)
  end
end

首先,调用范围返回一个 ActiveRecord::Relation 对象:

First, invoking a scope returns an ActiveRecord::Relation object:

Article.published.class
#=> ActiveRecord::Relation

Article.featured.class
#=> ActiveRecord::Relation

然后,您可以使用相应模型的类方法对 ActiveRecord::Relation 对象进行操作:

Then, you can operate on the ActiveRecord::Relation object using the respective model's class methods:

Article.published.featured.latest_article
Article.featured.titles

理解类方法和ActiveRecord::Relation之间的关系有点迂回,但要点是:

It's a bit of a roundabout way of understanding the relationship between class methods and ActiveRecord::Relation, but the gist is this:

  1. 根据定义,模型作用域返回 ActiveRecord::Relation 对象
  2. 根据定义,作用域可以访问类方法
  3. 因此ActiveRecord::Relation 对象可以访问类方法
  1. By definition, model scopes return ActiveRecord::Relation objects
  2. By definition, scopes have access to class methods
  3. Therefore, ActiveRecord::Relation objects have access to class methods

这篇关于ActiveRecord::Relation 对象如何调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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