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
rails-quick-guide.htm
广告
© . All rights reserved.