跳到內容 跳到搜尋
方法
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.klass
      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