原文參考:[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
本文介绍了一种使用Rails中named_scope的优雅方式来替代繁琐的find方法。通过对比两种不同的PostsController实现,展示了如何简化代码并提高其可读性和美观度。

被折叠的 条评论
为什么被折叠?



