加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:43:08 所属栏目:百科 来源:网络整理
导读:ActiveRecord :: Relation对象如何调用类方法? class Project ActiveRecord::Base has_many :tasksendclass Task ActiveRecord::Base belongs_to :project def self.initial_tasks # class methods # here return initial tasks endend 现在我们可以打电话
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对象可以访问类方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读