跳至内容 跳至搜索
方法
A
D
S

实例公共方法

all(all_queries: nil)

返回一个 ActiveRecord::Relation 作用域对象。

posts = Post.all
posts.size # Fires "select count(*) from  posts" and returns the count
posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects

fruits = Fruit.all
fruits = fruits.where(color: 'red') if options[:red_only]
fruits = fruits.limit(10) if limited?

你可以使用 default_scope 定义一个应用于所有查找的操作。

# File activerecord/lib/active_record/scoping/named.rb, line 22
def all(all_queries: nil)
  scope = current_scope

  if scope
    if self == scope.model
      scope.clone
    else
      relation.merge!(scope)
    end
  else
    default_scoped(all_queries: all_queries)
  end
end

default_scoped(scope = relation, all_queries: nil)

返回一个具有默认作用域的模型的作用域。

# File activerecord/lib/active_record/scoping/named.rb, line 45
def default_scoped(scope = relation, all_queries: nil)
  build_default_scope(scope, all_queries: all_queries) || scope
end

scope(name, body, &block)

添加一个用于检索和查询对象的类方法。该方法旨在返回一个 ActiveRecord::Relation 对象,该对象可以与其他作用域组合。如果返回 nilfalse,则会改用 all 作用域。

作用域代表数据库查询的缩小,例如 where(color: :red).select('shirts.*').includes(:washing_instructions)

class Shirt < ActiveRecord::Base
  scope :red, -> { where(color: 'red') }
  scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
end

scope 的上述调用定义了类方法 Shirt.redShirt.dry_clean_onlyShirt.red 实际上代表了查询 Shirt.where(color: 'red')

请注意,这仅仅是定义实际类方法的“语法糖”。

class Shirt < ActiveRecord::Base
  def self.red
    where(color: 'red')
  end
end

然而,与 Shirt.find(...) 不同的是,Shirt.red 返回的对象不是 Array,而是 ActiveRecord::Relation,它可以与其他作用域组合;它类似于由 has_many 声明构建的关联对象。例如,你可以调用 Shirt.red.firstShirt.red.countShirt.red.where(size: 'small')。同样,与关联对象一样,命名作用域的行为类似于 Array,实现了 EnumerableShirt.red.each(&block)Shirt.red.firstShirt.red.inject(memo, &block) 的行为都好像 Shirt.red 确实是一个数组。

这些命名作用域是可组合的。例如,Shirt.red.dry_clean_only 将返回所有既是红色又是干洗的衬衫。嵌套查找和计算也适用于这些组合:Shirt.red.dry_clean_only.count 返回满足这些标准的服装数量。同样,Shirt.red.dry_clean_only.average(:thread_count) 也是如此。

所有作用域都作为类方法在定义作用域的 ActiveRecord::Base 的后代上可用。但它们也对 has_many 关联可用。如果,

class Person < ActiveRecord::Base
  has_many :shirts
end

那么 elton.shirts.red.dry_clean_only 将返回 Elton 的所有红色、干洗衬衫。

命名作用域也可以具有扩展,就像 has_many 声明一样。

class Shirt < ActiveRecord::Base
  scope :red, -> { where(color: 'red') } do
    def dom_id
      'red_shirts'
    end
  end
end

创建/构建记录时也可以使用作用域。

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

Article.published.new.published    # => true
Article.published.create.published # => true

你的模型中的类方法自动对作用域可用。假设有以下设置:

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

我们可以像这样调用方法:

Article.published.featured.latest_article
Article.featured.titles
# File activerecord/lib/active_record/scoping/named.rb, line 154
def scope(name, body, &block)
  unless body.respond_to?(:call)
    raise ArgumentError, "The scope body needs to be callable."
  end

  if dangerous_class_method?(name)
    raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
      "on the model \"#{self.name}\", but Active Record already defined " \
      "a class method with the same name."
  end

  if method_defined_within?(name, Relation)
    raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
      "on the model \"#{self.name}\", but ActiveRecord::Relation already defined " \
      "an instance method with the same name."
  end

  extension = Module.new(&block) if block

  if body.respond_to?(:to_proc)
    singleton_class.define_method(name) do |*args|
      scope = all._exec_scope(*args, &body)
      scope = scope.extending(extension) if extension
      scope
    end
  else
    singleton_class.define_method(name) do |*args|
      scope = body.call(*args) || all
      scope = scope.extending(extension) if extension
      scope
    end
  end
  singleton_class.send(:ruby2_keywords, name)

  generate_relation_method(name)
end