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