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')
  end
end

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

class TasksController < ApplicationController
  def index
    @tasks = Task.find_incomplete
end

你一定看出来了,这种实现方式有一个限制,那就是我们无法再向方法中传递参数了,比如说我们想指定返回未完成任务中的前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
  end
end

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

posted on 2012-11-20 22:09  边晓宇  阅读(992)  评论(0编辑  收藏  举报