Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before_action for specific controller

class ApplicationController < ActionController::Base
      before_action :test, only: [:index]

      def test
          ap 'test'
      end
    end

The above is run before every single index action, be it dogs#index or cats#index or rabbits#index. How should I get it to execute just before cats#index and rabbits#index?

I want to test to be exectuted before actions in many controllers.

like image 258
Starkers Avatar asked Jun 16 '14 12:06

Starkers


People also ask

How should you use filters in controllers?

Filters are inherited, so if you set a filter on ApplicationController , it will be run on every controller in your application. The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run.

What does Before_action do in Rails?

When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.

What is application controller?

A centralized point for handling screen navigation and the flow of an application.

What is before action?

A 'before action review' (BAR) is a tool to help a team asses the current knowledge and experience they already have as a way to inform the planning stages of a new project.


2 Answers

You can skip this method:

class ApplicationController < ActionController::Base
  before_action :test, only: [:index]

  def test
    p 'test'
  end
end

class DogsController < ApplicationController
  skip_before_action :test
end
like image 190
user2503775 Avatar answered Sep 17 '22 23:09

user2503775


Just move your call into the controller you want it to run in.

class ApplicationController < ActionController::Base
  # nothing here!

  def test
    # ...
  end
end

class CatsController < ApplicationController
  before_action :test, only: [:index]
end

class RabbitsController < ApplicationController
  before_action :test, only: [:index]
end
like image 29
Edd Morgan Avatar answered Sep 17 '22 23:09

Edd Morgan