Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在创建Rails记录期间使用范围意味着什么?_Ruby On Rails_Activerecord_Scope - Fatal编程技术网

Ruby on rails 在创建Rails记录期间使用范围意味着什么?

Ruby on rails 在创建Rails记录期间使用范围意味着什么?,ruby-on-rails,activerecord,scope,Ruby On Rails,Activerecord,Scope,在解释以下示例中两次调用作用域做什么的文档中?第一组类似于Article.new('published':true)但是第二组published做什么呢 class Article < ActiveRecord::Base scope :published, -> { where(published: true) } end Article.published.new.published # => true 类文章{where(published:true)} 结

在解释以下示例中两次调用作用域做什么的文档中?第一组类似于
Article.new('published':true)
但是第二组
published
做什么呢

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

Article.published.new.published    # => true
类文章{where(published:true)}
结束
Article.published.new.published#=>正确

第二个
.published
不是作用域,它只是从新文章对象获取
:published
属性。代码的工作原理如下:

  • 第一个
    :published
    文章
    上调用,并返回一个对象
  • 然后对ActiveRecord::Relation对象()调用
    :new
    ,该对象返回一个新的
    文章
    ,该文章维护当前范围(在本例中类似于调用
    文章.new(published:true)
  • 第二个
    :published
    只是从我们的新文章中获取published属性,该属性已设置为
    true

  • 第二个
    .published
    不是作用域,它只是从新的Article对象获取
    :published
    属性。代码的工作原理如下:

  • 第一个
    :published
    文章
    上调用,并返回一个对象
  • 然后对ActiveRecord::Relation对象()调用
    :new
    ,该对象返回一个新的
    文章
    ,该文章维护当前范围(在本例中类似于调用
    文章.new(published:true)
  • 第二个
    :published
    只是从我们的新文章中获取published属性,该属性已设置为
    true

  • @这有助于澄清你的问题吗?如果是这样,你介意检查我的答案吗:)@stackjlei这有助于澄清你的问题吗?如果是的话,你介意检查我的答案吗:)