为Controller减肥

我们的Rails Controller中可能随处可见这样的代码:

class BBSController < ActionController::Base
  def index
    @users = User.find(:all, :o rder => "id desc",
                       :conditions => ['status=online'])
  end
end

这看起来没什么不对,但是设想一下,如果你在写完这段代码很久之后再次回头阅读它时,你很可能需要花点时间才能搞明白它是什么意思,那么为什么不让它看起来更直观一些呢?就像下面这样:

class User < ActiveRecord::Base
  def find_all_online
    find(:all, :o rder => “id desc”,
         :conditions => [’status=online’])
  end
end
class BBSController < ActionController::Base
  def index
    @users = User.find_all_online
  end
end

现在一切看起来是不是清楚多了?

This entry was posted in 其它. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

无觅相关文章插件,快速提升流量