原文參考:[url]http://rails-bestpractices.com/posts/1-move-finder-to-named_scope[/url]
壞習慣:
下面的代碼看了就讓人感覺不舒服,不但寫的繁雜,而且也不美觀...
我們可以用name_scope來拯救它...
清新一個伶俐一個燦爛一個,大嘴巴子抽Y的:[img]/images/guest_book/8.gif[/img]
壞習慣:
下面的代碼看了就讓人感覺不舒服,不但寫的繁雜,而且也不美觀...
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的:[img]/images/guest_book/8.gif[/img]
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