How to use rails before_action conditional for only some actions?

4.4k Views Asked by At

I have a controller with many actions (let's say action1, action2, action3, and action4). I have a before_action filter I'd like to exclude on some actions, close to:

before_action :filter_thing, except: [:action3, :action4]

However, I want the filter to be conditionally called for action2.

I tried simply splitting it into two before_actions but the second seemed to overwrite the first; in the following code filter_thing wasn't called for action1:

before_action :filter_thing, except: [:action3, :action4]
before_action :filter_thing, only: [:action2], unless: :should_not_filter?

I thought that maybe I could use a conditional skip_before_action:

skip_before_action :filter_thing, only: :action2, if: :should_not_filter?

but it seems to ignore the if: argument.

Is there a way to conditionally apply a filter to only some actions?

2

There are 2 best solutions below

0
Parker On

This is the workaround I came up with:

before_action :filter_thing,
              except[:action3, :action4],
              unless: -> { params[:action] == "action2" && should_not_filter? }

I'm still not wholly satisfied because the above is convoluted and tough to read.

0
Chrismisballs On

Late to the party but you could try this. Have not tested btw:

before_action :filter_thing, except: %i[action3 action4], unless: :filter_not

private

def filter_not
  action_name && should_not_filter?
end

action_name

From the api guide:

Returns the name of the action this controller is processing.