Search code examples
ruby-on-railscontrollerbefore-filteroperator-precedence

Rails: prepend_before_action in superclass


I have an authentication method in my ApplicationController that I always want to run first. I also have a method in an subcontroller that I want to run after the authentication method, but before the other ApplicationController before_actions. In other words, I want this:

ApplicationController
before_action first
before_action third

OtherController < ApplicationController
before_action second

The above causes the methods to be called in order of: first -> third -> second. But I want the order to go: first -> second -> third.

I've tried using prepend_before_action, like so:

ApplicationController
prepend_before_action first
before_action third

OtherController < ApplicationController
prepend_before_action second

But this causes it to go second -> first -> third.

How do I get the order to be first -> second -> third?


Solution

  • You can use the prepend_before_actionlike this:

    class ApplicationController < ActionController::Base
      before_action :first
      before_action :third
    end
    
    class OtherController < ApplicationController
      prepend_before_action :third, :second
    end