【译】爱上named_scope

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/14-love-named_scope

named_scope真是太棒了, 它让你的code更易读,同时你也可以结合named_scope finders做复杂的查询

丑陋的...

class PostsController < ApplicationController
  def search
    conditions = { :title => "%#{params[:title]}%" } if params[:title]
    conditions.merge! { :content => "%#{params[:content]}%" } if params[:content]

    case params[:order]
    when "title" : order = "title desc"
    when "created_at : order = "created_at desc"
    end

    @posts = Post.find(:all, :conditions => conditions, :order => order,
                 :limit => params[:limit])
  end
end

这样太丑了, 这是一个位于控制器中的复杂finder,包含了模糊查询,排序,limit,复杂的finder不应该在控制器中做,
我们应该把它用named_scope的方式放到模型中去

重构...

class Post < ActiveRecord::Base
  named_scope :matching, lambda { |column , value|
    return {} if value.blank?
    { :conditions => ["#{column} like ?", "%#{value}%"] }
  }

named_scope :order, lambda { |order|
    {
      :order => case order
      when "title" : "title desc"
      when "created_at" : "created_at desc"
      end
    }
  }

named_scope :limit, lambda { |limit|
    { :limit => limit }
  }
end

class PostsController < ApplicationController
  def search
    @posts = Post.matching(:title, params[:title])
     .matching(:content, params[:content])
     .order(params[:order]).limit(params[:limit])
  end
end

使用named_scope的优点 * 代码更具可读性, 方法调用, 我们能知道复杂的finder包含了各种各样的条件限制 *
遵循瘦控制器,胖模型, 这是MVC的核心原理 * 你可以方便的重用named_scope, 结合named scopes做复杂finder

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top