Search code examples
ruby-on-railsbefore-filter

Use action from a controller as filter in another controller in rails


I am trying to create an action that checks if a user is permitted to perform a certain action and if the user isn't then I want to redirect the user to an "Access Denied" view This is how my current setup is

class PermissionController < ApplicationController

def authorize(permission_id)
   is_permitted = is_user_permitted(permission_id)
   respond_to do |format|
     format.js { render :json => {:is_permitted => is_permitted, :redirect => url_for(:controller => 'welcome', :action => 'index' , notice: "No access")}}
     format.all  { redirect_to :controller => 'welcome', :action => 'index' , notice: "No access" unless is_permitted == true }
   end
end

end

I want to call the authorize action in the :before_filter of another controller.

How do I do that?

I can't put the authorize action in the ApplicationController since I want to define a route to this action in routes.rb


Solution

  • @NickM has covered this in his comment... have OtherController inherit from PermissionController

    class PermissionController < ApplicationController
      def authorize
        ...
      end
    end
    
    class OtherController < PermissionController
      before_filter :authorize
    end
    

    However I note your authorize method has a parameter?

    You'll need to handle that in the before_filter clause. Assuming you can store permission_id in a session variable...

    class PermissionController < ApplicationController
      def authorize(permission_id)
        ...
      end
    end
    
    class OtherController < PermissionController
      before_filter { |controller| controller.authorize(session[:permission_id] }
    end