Ruby-on-rails-rails-with-scope
提供:Dev Guides
Ruby on Rails-with_scopeのネスト
この例は、要件に基づいてさまざまな結果を取得するために 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
前のスコープがどのように無視されるかを示すもう1つの例。
# 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