Ruby on Rails - imbriqué avec_scope

Cet exemple montre comment nous pouvons imbriquer with_scope pour récupérer différents résultats en fonction des besoins.

# 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

Maintenant, regardez un autre exemple de la façon dont la portée est cumulative.

# 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

Un autre exemple qui montre comment la portée précédente est ignorée.

# 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
rails-references-guide.htm