用named_scope代替繁瑣的finder

原文參考: http://rails-bestpractices.com/posts/1-move-finder-to-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


我們可以用name_scope來拯救它...
清新一個伶俐一個燦爛一個,大嘴巴子抽Y的:
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

你可能感兴趣的:(sql,Ruby,Rails,ActiveRecord)