Ruby-on-rails-2.1-rails-with-scope

提供:Dev Guides
移動先:案内検索

Ruby on Rails 2.1-スコープ付きネスト

次の例は、 with_scope をネストして、要件に基づいてさまざまな結果を取得する方法を示しています。

# SELECT *FROM employees
# WHERE (salary > 10000)
# LIMIT 10
# Will be written as
Employee.with_scope(
   :find => { :conditions => "salary > 10000",
   :limit => 10 }) do
   Employee.find(:all)
end

次に、スコープの累積方法を示す別の例を確認します。

# SELECT* FROM employees
# WHERE ( salary > 10000 )
# AND ( name = 'Jamis' ))
# LIMIT 10
# Will be written as
Employee.with_scope(
   :find => { :conditions => "salary > 10000",
   :limit => 10 }) do
   Employee.find(:all)
   Employee.with_scope(
      :find => { :conditions => "name = 'Jamis'" }) do
      Employee.find(:all)
   end
end

次の例は、前のスコープがどのように無視されるかを示しています。

# SELECT * FROM employees
# WHERE (name = 'Jamis')
# is written as
Employee.with_scope(
   :find => { :conditions => "salary > 10000",
   :limit => 10 }) do
   Employee.find(:all)
   Employee.with_scope(
      :find => { :conditions => "name = 'Jamis'" }) do
      Employee.find(:all)
   end
   # all previous scope is ignored
   Employee.with_exclusive_scope(
      :find => { :conditions => "name = 'Jamis'" }) do
      Employee.find(:all)
   end
end