Rails宝典之第五式: 使用with_scope

这次来介绍with_scope方法的使用。 

继续前面的例子,我们希望只取得complete为false的前20条数据,我们可以给find_incomplete方法添加一个Hash参数,然后使用with_scope将 
额外的参数附加到我们的查询方法里: 
Java代码   收藏代码
  1. class Task < ActiveRecord::Base  
  2.   belongs_to :project  
  3.   
  4.   def self.find_incomplete(options = {})  
  5.     with_scope :find => options do  
  6.       find_all_by_complete(false, : order => 'created_at DESC')  
  7.     end      
  8.   end  
  9. end  
  10.   
  11. class TasksController < ApplicationController  
  12.   def index  
  13.     @tasks = Task.find_incomplete :limit => 20  
  14.   end  
  15. end  
  16.   
  17. class ProjectsController < ApplicationController  
  18.   def show  
  19.     @project = Project.find(params[:id])  
  20.     @tasks = @project.tasks.find_incomplete :limit => 20  
  21.   end  
  22. end  

这样我们就可以在TasksController和ProjectsController里使用:limit来限定取前20条数据了 

不过这样使用with_scope有一个缺点,就是我们不能在调用find_incomplete时指定: order条件来覆盖该方法定义时默认的: order条件 
能不能改进一下我们的find_incomplete方法来解决这个问题呢? 
很简单,我们可以将额外的参数merge进来: 
Java代码   收藏代码
  1. class Task < ActiveRecord::Base  
  2.   belongs_to :project  
  3.   
  4.   def self.find_incomplete(options = {})  
  5.     find_all_by_complete(false, {: order => 'created_at DESC'}.merge(options))  
  6.   end  
  7. end  

或者使用ActiveSupport对Hash的扩展方法reverse_merge: 
Java代码   收藏代码
  1. class Task < ActiveRecord::Base  
  2.   belongs_to :project  
  3.   
  4.   def self.find_incomplete(options = {})  
  5.     find_all_by_complete(false, options.reverse_merge(: order => 'created_at DESC'))  
  6.   end  
  7. end  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值