Ordering of before_action filters in Rails controllers

Posted . Visible to the public.

It turns out that the before_action filters has some special behavior that is not intuitive.

Here are two controllers, with ImagesController inheriting from AdminController.
You'll notice that both have 'before_action: :authenticate_admin!' What do you think will happen when ImagesController#index is called?


class AdminController < ApplicationController
  before_action :authenticate_admin!
  before_action :set_admin_table_vars, only: [:index, :create, :update]
  ...
end

class Admin::Content::ImagesController < AdminController
  before_action :authenticate_admin!
  ...
end

The intuitive response is that the actions are run in this order:
authenticate_admin!
set_admin_table_vars
authenticate_admin!

Unfortunately, Rails seems to be set so that the authenticate_admin! is called only once, with the subclass before_actions. Thus, if there's anything inside the before_action chain of AdminController that needs to check first authenticated admin, it will fail because the user has not been authenticated.

Surprising behavior!

If you don't need authenticate_admin to run after the AdminController filters, you could remove authenticate_admin! from the subclass

If you need something more complicated, you can use some of the other callback methods Show archive.org snapshot .

Profile picture of mcsheu
mcsheu
Last edit
mcsheu
Posted by mcsheu to mcsheu's deck (2016-04-26 22:34)