2011-02-02 84 views
2

如果我生成一个脚手架,我会得到标准动作索引,新的,显示,创建....所有这些都包含一行,例如,像在控制器中重构生成的操作代码

@comment = Comment.find(params[:id]) 

是否有意义把这个线在一个单独的方法到像

def load 
@comment = Comment.find(params[:id]) 
end 

控制器这是一个优势? THX您的时间

回答

2

是在单独的方法,并且还肯定的使用的before_filter。

class CommentsController < ApplicationController 
    # Whitelist your before_filter like this. Or you can blacklist it with :except => [] 
    before_filter :load_comment, :only => [:edit, :update, :destroy, :show] 

    def show 
    end 

    def index 
    @comments = Comment.all 
    end 

    def new 
    @comment = Comment.new 
    end 

    # etc ... 

    protected 

    def load_comment 
    @comment = Comment.find(params[:id]) 
    end 
end 
+0

嘿thx为您的答复。为什么要保护它?以及如果我在我的操作中已经有了不同的查询,如“@comment = Comment.new”。 before_filter覆盖它吗?我是在我的操作方法之前还是在我的控制器的末端放置方法? – daniel 2011-02-02 01:21:22

相关问题