2014-06-16 3 views
4
class ApplicationController < ActionController::Base 
     before_action :test, only: [:index] 

     def test 
      ap 'test' 
     end 
    end 

위의 코드는 dog # index 또는 cats # index 또는 rabbits # index가 될 때마다 실행됩니다. cat # index와 rabbit # index 바로 전에 어떻게 실행해야합니까?특정 컨트롤러의 before_action

많은 컨트롤러에서 작업 전에 실행되도록 테스트하고 싶습니다.

답변

3

그냥 당신이에서 실행하려는 컨트롤러에 전화를 이동

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 
+3

을 컨트롤러이 작업의 재치있는 하위 범주가있는 경우 적용될 때 상속 체인에 소개 할 수 있습니다 :'class FluffyPetsController DaveMongoose

+2

^좋은 추가. 어떤 상황에서는이 호출에서'before_action'을 섞는 모듈을 요구할 수도 있습니다. ('클래스 CatsController

+0

http://stackoverflow.com/questions/11940253/where-to-put-a-before-filter-shared-between-multiple-controllers 예제를 제공합니다. 모듈 기반 솔루션 – DaveMongoose

6

당신은이 방법을 건너 뛸 수 있습니다.

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

    def test 
    p 'test' 
    end 
end 

class DogsController < ApplicationController 
    skip_before_action :test 
end 
+0

인증하는 경우 이것이 좋을 것이라고 생각합니다. – Starkers

+0

정답은 내 생각입니다. – FloatingRock

관련 문제