Ruby on Rails 2.1 - 嵌套 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