【译】把finder移到模型中的named_scope

Saturday, July 24, 2010

原文:http://rails-bestpractices.com/posts/1-move-finder-to-named_scope

在控制器中写复杂的查询使得程序很难维护,把他们以named_scope方式写到模型中可以把控制器变得简单易读,使得所有的复杂逻辑查询都在模型中

丑陋的...

class PostsController < ApplicationController
  def index
    @published_posts = Post.find(:all, :conditions => { :state => 'published' },
                           :limit => 10,
                           :order => 'created_at desc')

@draft_posts = Post.find(:all, :conditions => { :state => 'draft' },
                       :limit => 10,
                       :order => 'created_at desc')
  end
end

在这个例子中, PostsController用了两个复杂的finder来得到已发布的文章和草稿: 1.
在控制器方法中包含复杂的finder通常很长,使得控制器的可读性很差 2. 同样的finder可能会在不同的控制器中用到它,
如果finder的逻辑需要修改,那你就得去不同的控制器中做同样的修改,这样很可能就产生了

重构...

class PostsController < ApplicationController
  def index
    @published_posts = Post.published
    @draft_posts = Post.draft
  end
end

class Post < ActiveRecord::Base
  named_scope :published, :conditions => { :state => 'published' },
              :limit => 10,
              :order => 'created_at desc'
  named_scope :draft, :conditions => { :state => 'draft' },
          :limit => 10,
          :order => 'created_at desc'
end

现在, 我们把这两个finder从控制器移到了模型中, 和你看到的那样, 控制器变得简单易读, 把复杂的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