`
fireflyman
  • 浏览: 113361 次
  • 性别: Icon_minigender_1
  • 来自: 火星
社区版块
存档分类
最新评论

用named_scope代替繁瑣的finder

    博客分类:
  • ROR
阅读更多
原文參考: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

分享到:
评论
9 楼 yuan 2010-07-28  
           
8 楼 Hooopo 2010-07-28  
yuan 写道
named_scope的好处主要在于可以“串”起来,更加的DRY。在知道named_scope之前我是直接写一个方法来封装这个finder,一样可以很直观:
def published
  all(:conditions => {:state => 'published'}, :limit => 10, :order => 'created_at desc')
end

但是不能“串”起来

其实最大好处不是串起来。。
是提供lazy load特性。。橡这样的写法只执行一条sql:
Post.published.all(:conditions => "id > 1")

同样,关联也是这样....
7 楼 yuan 2010-07-27  
named_scope的好处主要在于可以“串”起来,更加的DRY。在知道named_scope之前我是直接写一个方法来封装这个finder,一样可以很直观:
def published
  all(:conditions => {:state => 'published'}, :limit => 10, :order => 'created_at desc')
end

但是不能“串”起来
6 楼 fireflyman 2010-07-27  
Hooopo 写道
笨笨狗 写道
介个,不都是常识么,囧……

我都说是常识了,,可是他说他们java不一样。。。

你是說燕子kaka他們
5 楼 Hooopo 2010-07-27  
笨笨狗 写道
介个,不都是常识么,囧……

我都说是常识了,,可是他说他们java不一样。。。
4 楼 fireflyman 2010-07-27  
其實....我只是寫下來當記錄用....


各位兄弟不要激動...
3 楼 笨笨狗 2010-07-27  
介个,不都是常识么,囧……
2 楼 贫嘴男孩 2010-07-27  
虎炮说你们把业务逻辑都放在model里了
1 楼 orcl_zhang 2010-07-26  
你已经凹凸了。

相关推荐

Global site tag (gtag.js) - Google Analytics