Ruby on Rails - aninhado com_scope

Este exemplo mostra como podemos aninhar with_scope para buscar resultados diferentes com base nos requisitos.

# 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

Agora, verifique outro exemplo de como o escopo é cumulativo.

# 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

Mais um exemplo que mostra como o escopo anterior é ignorado.

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