2013-05-21 3 views

답변

2

한 번의 작업에서 여러 컨트롤러가 사용된다고 말하면 더 구체적 일 수 있습니까? 일반적으로 액션을 담당하는 컨트롤러의 before_filter로 충분합니다.

필터를 여러 컨트롤러의 특정 메서드에 적용하려면 메서드 자체를 ApplicationController에두고 before_filter는 작업을 포함하는 각 컨트롤러에 배치합니다.

class ApplicationController 
    def foo 
    @bar = 'bar' 
    end 
end 

class UserController 
    before_filter :foo, :only => [:method1] 

    def method1 
    ... 
    end 

    def method2 
    ... 
    end 
end 

class StuffController 
    before_filter :foo, :only => [:method2] 

    def method1 
    ... 
    end 

    def method2 
    ... 
    end 
end 

class UnimportantController 
    # No before filter, neither of these methods will call :foo 

    def method1 
    ... 
    end 

    def method2 
    ... 
    end 
end 
+0

즉 내가 AJAX에 의한 PageController 및 CommentController ... normaly PageController 부하와 CommentController로드가 각 페이지 아래에 의견을 렌더링합니다. 이것이 둘 다 ApplicationController의 before_filter를 실행하고 before_filter를 호출하는 이유입니다. 내가 잘못? –

+0

앞에서 제안한대로 before_filters를 사용하여 PageController의 중요한 동작 만 제한하십시오. 메스와 해머 해머 접근 방식이 더 중요합니다. 필터가없는 세 번째 컨트롤러 예제를 추가했습니다. – Matt

+0

before_filter를 실행하지 않으려면 xhr 호출 (응답에 설명 된 특정 작업이 아님)에 대해 여기에 설명 된대로 수행 할 수 있습니다. http://stackoverflow.com/questions/5114529/is-there-a -way-in-rails-to-skip-a-before-filter-if-the-request-is-xhr –

관련 문제