原创作者: hideto   阅读:1364次   评论:0条   更新时间:2011-05-26    
这次来介绍with_scope方法的使用。

继续前面的例子,我们希望只取得complete为false的前20条数据,我们可以给find_incomplete方法添加一个Hash参数,然后使用with_scope将
额外的参数附加到我们的查询方法里:
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

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

不过这样使用with_scope有一个缺点,就是我们不能在调用find_incomplete时指定: order条件来覆盖该方法定义时默认的: order条件
能不能改进一下我们的find_incomplete方法来解决这个问题呢?
很简单,我们可以将额外的参数merge进来:
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

或者使用ActiveSupport对Hash的扩展方法reverse_merge:
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
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics