고유하지 않은 적합성으로 Ruby on Rails를 사용하여 블로그 애플리케이션을 작성하고 있습니다. 내 PostsController
에는 로그인 한 사용자가 자신의 게시물 만 편집하거나 삭제할 수있는 코드가 포함되어 있습니다.레일 : 사용자 스푸핑 체크 유지 DRY
이 코드를 표시 할 플래시 메시지에 대한 단일 인수가 포함 된 개인 메서드로 분해하려고 시도했지만 다른 작성자의 게시물을 편집하여 테스트했을 때 ActionController::DoubleRenderError
- "렌더링 또는 리디렉션 만 가능합니다. 하나의 행동 당 한 번 ".
어떻게 이러한 점검을 할 수 있습니까? 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 개의 검색어를 만듭니다. 사용자가 권한이 있는지 여부를 확인하기 전에 찾기를 수행하십시오. –