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

另一个示例,该示例展示了如何忽略以前的范围。

# 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
广告