首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

RailsCasts中文版,五 Using with_scope 对find方法限定作用域

2012-11-25 
RailsCasts中文版,#5 Using with_scope 对find方法限定作用域这次,我们讨论一下with_scope方法。下面的Task

RailsCasts中文版,#5 Using with_scope 对find方法限定作用域

这次,我们讨论一下with_scope方法。下面的Task中定义了一个返回所有未完成任务的类方法find_incomplete

class Task < ActiveRecord::Base  belongs_to :project  def self.find_incomplete    find_all_by_complete(false, :order => 'created_at DESC')  endend

在控制器TasksController中可以这么调用:

class TasksController < ApplicationController  def index    @tasks = Task.find_incompleteend

你一定看出来了,这种实现方式有一个限制,那就是我们无法再向方法中传递参数了,比如说我们想指定返回未完成任务中的钱20个。

@tasks = Task.find_incomplete :limit => 20

我们可以通过让Task中的find_incomplete接受一个哈希参数;然后再方法实现中将传入的参数合并后传入find方法来实现这个功能。当然了,有更优雅的实现方式那就是使用find_scope方法向find方法传递参数。

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  endend

find方法执行时会连同with_scope中指定的条件。这样一来find_incomplete方法就能携带任何传入的过滤条件参数了。这一特性在其他的作用域内也能生效。下面的代码中,我们传入了限制结果数量的参数。find方法传入了两层作用域:第一层是得到指定项目中的所有未完成任务,第二层是结果限制返回前20个。

@tasks = @project.tasks.find_incomplete :limit => 20


作者授权:You are welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.

原文链接:http://railscasts.com/episodes/5-using-with-scope?view=asciicast

热点排行