【问题标题】:What does it mean to use scope during creation of a Rails record?在创建 Rails 记录期间使用范围是什么意思?
【发布时间】:2017-06-23 00:09:51
【问题描述】:

在解释scope 的文档中,在下面的示例中两次调用作用域是做什么的?第一组就像Article.new('published': true),但第二组published 是做什么的?

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

Article.published.new.published    # => true

【问题讨论】:

    标签: ruby-on-rails activerecord scope


    【解决方案1】:

    第二个.published 不是作用域,它只是从新的Article 对象中获取:published 属性。代码是这样工作的:

    1. 第一个:publishedArticle 上调用并返回一个ActiveRecord::Relation 对象
    2. 然后在 ActiveRecord::Relation 对象 (Docs for ActiveRecord::Relation#new) 上调用 :new,该对象返回一个新的 Article,它维护当前范围(在我们的例子中类似于调用 Article.new(published: true)
    3. 第二个:published 只是从我们的新文章中获取已发布的属性,该属性已设置为true

    【讨论】:

    • @stackjlei 这有助于澄清您的问题吗?如果是这样,您介意检查我的答案吗:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2019-04-08
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多