2015-05-04 111 views
0

我正在創建REST API並在REST API中使用授權。只要用戶沒有被授權的行動就用下面的代碼CanCan Rails授權

rescue_from CanCan::AccessDenied do |exception| 
    redirect_to "/", :alert => exception.message 
end 

對於REST API方法重定向到主頁,我不希望被重定向到未經授權的訪問此頁面。相反,我想顯示json

{「Error_msg」:「Not Authorized」}。

我的控制器已經以下代碼:

authorize_resource :class => false, :only => [:create_or_update] 

其中create_or_update是其上我想要查詢的授權的動作(方法)。

我ability.rb已editor作用

can :create_or_update, :topology 

下面的代碼有人可以幫助我沒有得到重定向到主頁只爲這一行動。

回答

0
rescue_from CanCan::AccessDenied do |exception| 
if exception.action.to_s == "create_or_update" 
    err ={} 
    err[:error_id] = "AUTHORIZATION_ERROR" 
    err[:error_msg] = exception.message 
    render json: err, status: 403 
else 
    redirect_to "/", :alert => exception.message 
end 
end 
2

可以使用做的respond_to

rescue_from CanCan::AccessDenied do |exception| 
    respond_to do |format| 
     format.json { render(json: {"Error_msg": "Not Authorized"}, status: :forbidden)} 
     format.html{ 
     redirect_to "/", :alert => exception.message 
     } 
    end 
    end