ruby-on-rails – ActiveRecord :: Relation对象如何调用类方法

ActiveRecord :: Relation对象如何调用方法
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是一个方法,我们不能在对象上调用方法.

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

请解释.

解决方法

关于ActiveRecord :: Relation对象的类方法的应用程序没有太多的文档,但是我们可以通过看看 ActiveRecord scopes的工作原理来理解这个行为.

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

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对象:

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

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

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

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

了解类方法与ActiveRecord :: Relation之间的关系有一个迂回的方法,但这一点是:

>根据定义,模型范围返回ActiveRecord :: Relation对象>根据定义,范围可以访问类方法>因此,ActiveRecord :: Relation对象可以访问类方法

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...