2012-05-15 3 views
0

게시물 컨트롤러에 대한 내 코드는 다음과 같습니다. 내가하려는 것은 사용자가 자신의 게시물을 삭제할 수 있어야하고 admin_user는 모든 게시물을 삭제할 수 있어야한다는 것입니다. 다음 코드는 admin_user가 게시물을 삭제할 수 있도록하지만, 일반 사용자의 경우 자신의 게시물을 삭제하려고 할 때 root_path로 리디렉션합니다.before_filter에서 두 가지 방법을 실행하는 방법은 무엇입니까?

do_authentication이 제대로 작동하지 않는 것 같습니다. 일반 사용자는 관리자로 인증하려고합니다. "correct_user"대신

무엇이 잘못 될 수 있습니까?

감사합니다.

class PostsController < ApplicationController 
    before_filter :signed_in_user, only: [:index, :create, :destroy] 
    before_filter :do_authentication, only: :destroy 
    . 
    . 
    . 
def destroy 
    @post.destroy 
    flash[:success] = "Post deleted!" 
    redirect_back_or user_path(current_user) 
end 

private 
    def do_authentication 
    correct_user || admin_user 
    end 

    def correct_user 
    @post = current_user.posts.find_by_id(params[:id]) 
    redirect_to user_path(current_user) if @post.nil? 
    end 

    def admin_user 
    @post = Post.find_by_id(params[:id]) 
    redirect_to(root_path) unless current_user.admin? 
    end 

답변

0

우선 저는 승인을 위해 cancan을 사용할 것을 제안합니다. 귀하의 문제는 correct_user의 반환 값이라고 생각합니다. 당신은 그것을 통제하지 않습니다. 이 메소드가 false로 평가하는 것을 리턴하면 do_authentication 메소드는 admin_user도 호출합니다. 또한 시도 ... 관리자 권한도 작동하지 않습니다 보인다 코드에서

을 찾고이 :

def do_authentication 
    @post = Post.find_by_id(params[:id]) 
    redirect_to redirect_location unless current_user.admin? or @post.user == current_user 
end 

def redirect_location 
    return "redirect_location_for_admin" if current_user.admin? 
    return "redirect_location_for_non_admins" 
end 
+0

감사합니다. 나는 마침내 작동하는 방법을 찾는다. 사실 내가 생각했던 것보다 쉽다. def do_authentication current_user.admin이라면? @ post = post.find_by_id (params [: id]) else @ post = current_user.posts.find_by_id (params [: id]) redirect_to user_path (current_user) if @ post.nil? 끝 끝 – alexZ

0

방법의 correct_user,이를 admin_user에 관계없이 자신의 역할의 모든 사용자에 대해 실행되기 때문에 메소드를 호출하는 동안 조건을 확인하지 않았습니다. 문제를 해결하려면 코드를 개선해야합니다.

def do_authentication 
    if current_user.admin? 
    @post = Post.find_by_id(params[:id]) 
    else 
    @post = current_user.posts.find_by_id(params[:id]) 
    redirect_to user_path(current_user), :notice => "Access denied" unless @post 
    end 
end