Before action callback in Rails has support to add conditions like if and unless. The callback is executed only if the conditions evaluate to true. But, skip_before_action callback does not support conditionals. In this article we will learn how to skip certain action based on some condition.
callback supports conditional.
we have a
ProductsController as given below.
Now, let’s say, we want to run some code before
based on some condition.
this_is_true method will be executed before every action of the controller.
As, the method returns true, the controller action will get executed.
skip_before_action callback supports callbacks (methods)
to be skipped.
It supports two options.
- only - The callback should be run only for this action.
- except - The callback should be run for all actions except this action.
before_action callback supports conditional options
people tend to assume
skip_before_action would support
these two conditionals.
But, that’s not the case.
skip_before_action with condition (workaround)
Let’s take the same example as given above to skip before action for some condition.
It can be written as given below.
Interpretation and conclusion
execute_thiscallback will be skipped by default.
execute_thiscallback will be execute if
In order to achive conditional on
add the negative conditional on
skip_before_action is added before
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox