私はRuby on Railsを使用してブログアプリケーションを作成しています。私のPostsController
には、ログインしたユーザーが自分の投稿だけを編集または削除できるようにするコードが含まれています。Rails:ユーザーのなりすましのチェックDRY
私は表示するフラッシュメッセージのための単一の引数でプライベートメソッドに出て、このコードを因数分解しようとしたが、私はこれをしなかったし、別の著者の記事を編集して、それをテストしたとき、私はActionController::DoubleRenderError
だ - 「のみレンダリングまたはリダイレクトすることができます1回のアクションにつき1回。
これらのチェックはどうすればいいですか?DRY?明白な方法は、beforeフィルタを使用することですが、destroy
メソッドは異なるフラッシュを表示する必要があります。ここで
は、関連するコントローラのコードです:
before_filter :find_post_by_slug!, :only => [:edit, :show]
def edit
# FIXME Refactor this into a separate method
if @post.user != current_user
flash[:notice] = "You cannot edit another author’s posts."
redirect_to root_path and return
end
...
end
def update
@post = Post.find(params[:id])
# FIXME Refactor this into a separate method
if @post.user != current_user
flash[:notice] = "You cannot edit another author’s posts."
redirect_to root_path and return
end
...
end
def destroy
@post = Post.find_by_slug(params[:slug])
# FIXME Refactor this into a separate method
if @post.user != current_user
flash[:notice] = "You cannot delete another author’s posts."
redirect_to root_path and return
end
...
end
private
def find_post_by_slug!
slug = params[:slug]
@post = Post.find_by_slug(slug) if slug
raise ActiveRecord::RecordNotFound if @post.nil?
end
認証チェックの前にクエリを作成しないでください! –
@Pedro特定モデルのコピーを取得する前に、特定のモデルに基づいて認証(認証ではない)を確認する方法を説明しなければなりません。 :) –
あなたの認証方法は0の質問をします。 ユーザーが権限を持っているかどうかを確認する前に、検索を行います。 –