开发者

refactoring generated action code in the controller

If I generate a scaffold I get the standard actions index, new, show, create .... all of which contain a line e.g. like

@comme开发者_Python百科nt = Comment.find(params[:id])

Does it make sense to put this line in a seperate method into the controller like

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

Is this an advantage? Thx for your time


Yes to the separate method, and also yes to using a 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜