Tutorials Point


  Learning Ruby on Rails 2.1
  Advanced Ruby on Rails 2.1
  Ruby on Rails Quick Guide
  Ruby Tutorial
  Ruby on Rails Resources
  Selected Reading

Copyright © 2014 by tutorialspoint



  Home     References     Discussion Forums     About TP  

Ruby on Rails 2.1 - Nested with-scope


previous next AddThis Social Bookmark Button

Advertisements

This examples shows how we can nest with_scope to fetch different results based on requirements.

# 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

Now check another example how scope is 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

One more example which shows how previous scope is ignored.

# 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

Check the following link for more detail on Nested with_scope



previous next Printer Friendly

Advertisements


  

Advertisements