How to rescue by passing a block in Ruby? -
i have defined own method authorize_user
in 1 of controllers, as:
def authorize_user if !((current_user.has_role? :admin, @operator) || (current_user.has_role? :super_admin)) raise cancan::accessdenied end end
i want rescue cancan exception (or other exception matter). have used rolify in app. how rescue , redirect root_url
of app custom message?
i have tried following options, none of them worked:
try 1:
rescue cancan::accessdenied |exception| redirect_to root_url, :alert => exception.message end
error in case: syntax error, unexpected keyword_do, expecting '('
try 2:
rescue cancan::accessdenied redirect_to root_url, :alert => "unauthorized access"
error in case: render and/or redirect called multiple times in action
how solve issue?
this controller code:
class cabscontroller < applicationcontroller before_action :set_cab, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! after_action :authorize_user # basic crud actions private def set_cab @cab = cab.find(params[:id]) @operator = operator.find(params[:operator_id]) end def cab_params params.require(:cab).permit(:category, :number) end def authorize_user if !((current_user.has_role? :admin, @operator) || (current_user.has_role? :super_admin)) raise cancan::accessdenied end end end
i think try rescue_from
method.
for example, applicationcontroller
, this:
class applicationcontroller < actioncontroller::base rescue_from cancan::accessdenied, with: :not_authorized #other stuff private def not_authorized redirect_to root_url, alert: "unauthorized access" end end
since question updated more code, here additional information:
some suggestions:
- make
:authorize_user
before_action
well. way don't need worry code running in action when user not allowed stuff. - you might need add same
:only
option:set_cab
since use@operator
instance variable. - last, personal code style preference have changed
if !
unless
increase reading flow.
Comments
Post a Comment