フィルターの中でfindしたモデルを使う
権限チェック処理をフィルターで行ってみる。
権限チェックを行うためには、対象のモデルをfindする必要があるのだが、取得したモデルをそのままアクションの方でも使いたい。。。
→インスタンス変数にすればOK。
ただし、アクションの中でいきなりインスタンス変数が出てくるのでちょっと困惑するかも。
class CommentController < ApplicationController # コメント編集権限の認証 before_filter :filter_comment_editable, :only => ["edit", "delete"] def edit ActiveRecord::Base.transaction do # 権限チェックのフィルターで@commentを取得 @comment.update_attributes!(params[:comment]) #<------いきなり@commentが出現する end flash[:notice] = "コメントを編集しました" redirect_to :controller => 'topic', :action => 'show', :id => params[:comment][:topic_id] end private # コメント編集権限チェック処理フィルタ def filter_comment_editable @comment = Comment.find(params[:comment][:id]) raise unless comment_editable?(@comment) end end