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

查看:43
本文介绍了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的类方法的文档并不多:关系对象,但我们可以通过查看 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天全站免登陆