Reputation: 133
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_action
s 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?
Upvotes: 5
Views: 4750
Reputation: 320
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
From the api guide:
Returns the name of the action this controller is processing.
Upvotes: 1
Reputation: 133
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.
Upvotes: 4