2012-05-15 12 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 if current_user.admin? (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 
相關問題