max
max

Reputation: 167

How to set a before_action only for default RESTful actions in Rails controller?

I have a controller with the default RESTful route actions (index new create show edit update destroy) and also several other actions. I want to set a before_action that only runs on the default routes.

I know I can add before_action :set_x, only: [:index, :new, :create, :show, :edit, :update, :destroy] to the top of the controller but is there a quicker way to do this? I'd like to do this for multiple controllers, so I cannot do before_action :set_x, except: [:foo, :bar, :baz] because the actions change in each controller and new actions are added all the time.

Thanks!

Upvotes: 0

Views: 804

Answers (1)

nathanvda
nathanvda

Reputation: 50057

Options:

  • define the before_action in the ApplicationController
  • write skip_before_action in those controllers that do not need it
  • define another "controller"-class, that derives from ApplicationController, add the before_action and only those controllers that need it, will inherit from that class
  • create a module with only the before_action and include it

Upvotes: 1

Related Questions