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
# 所有先前的范围都被忽略
Employee.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
Employee.find(:all)
end
end

rails-references-guide.html