Rails宝典之第五式: 使用with_scope

本文介绍了Rails中with_scope方法的应用,通过示例展示了如何使用with_scope来限制查询条件,并讨论了如何解决自定义查询条件覆盖默认条件的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

继续前面的例子,我们希望只取得complete为false的前20条数据,我们可以给find_incomplete方法添加一个Hash参数,然后使用with_scope将
额外的参数附加到我们的查询方法里:
[code]
class Task < ActiveRecord::Base
belongs_to :project

def self.find_incomplete(options = {})
with_scope :find => options do
find_all_by_complete(false, : order => 'created_at DESC')
end
end
end

class TasksController < ApplicationController
def index
@tasks = Task.find_incomplete :limit => 20
end
end

class ProjectsController < ApplicationController
def show
@project = Project.find(params[:id])
@tasks = @project.tasks.find_incomplete :limit => 20
end
end
[/code]
这样我们就可以在TasksController和ProjectsController里使用:limit来限定取前20条数据了

不过这样使用with_scope有一个缺点,就是我们不能在调用find_incomplete时指定: order条件来覆盖该方法定义时默认的: order条件
能不能改进一下我们的find_incomplete方法来解决这个问题呢?
很简单,我们可以将额外的参数merge进来:
[code]
class Task < ActiveRecord::Base
belongs_to :project

def self.find_incomplete(options = {})
find_all_by_complete(false, {: order => 'created_at DESC'}.merge(options))
end
end
[/code]
或者使用ActiveSupport对Hash的扩展方法reverse_merge:
[code]
class Task < ActiveRecord::Base
belongs_to :project

def self.find_incomplete(options = {})
find_all_by_complete(false, options.reverse_merge(: order => 'created_at DESC'))
end
end
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值