2012-02-17 4 views
11

indexshow 두 가지 동작이 정의 된 레일 컨트롤러가 있습니다. index 액션에 인스턴스 변수가 정의되어 있습니다.컨트롤러의 모든 동작에 대해 동일한 인스턴스 변수

def index 
    @some_instance_variable = foo 
end 

def show 
    # some code 
end 

가 어떻게이 @some_instance_variableshow.html.erb 템플릿에 액세스 할 수 있습니다 : 코드는 무엇인가 아래처럼?

답변

10

액션을 index 액션에서 렌더링하지 않는 한 표시 액션에서 @some_instance_variable을 설정해야합니다. 컨트롤러 동작이 호출되면 일치하는 메서드가 호출되므로 show 동작을 사용할 때 index 메서드의 내용이 호출되지 않습니다. 당신이 모두 indexshow 행동에서 같은 일을 @some_instance_variable 설정이 필요하면

은 올바른 방법은 인스턴스 변수를 설정 indexshow 모두라는 또 다른 방법을 정의하는 것입니다.

def index 
    set_up_instance_variable 
end 

def show 
    set_up_instance_variable 
end 

private 

def set_up_instance_variable 
    @some_instance_variable = foo 
end 

set_up_instance_variable 방법을 비공개로 만들기는 와일드 카드 경로가있는 경우 컨트롤러 액션이라 할 수없는 (즉, match ':controller(/:action(/:id(.:format)))')

+1

Thanks @Emily. 그러나 이것을하기위한 건조한 방법이 있습니까? – Red

+0

감사합니다. @Emily 나는 똑같은 것을 찾고있었습니다. 건배! – Aashish

+0

'before_action : set_up_instance_variable, only : [: show, : index]'를 컨트롤러에 추가하십시오. 그것은 당신이 지정하는 동작 전에'set_up_instance_variable'을 실행합니다. – domi91c

52

당신은

class FooController < ApplicationController 
    before_filter :common_content, :only => [:index, :show] 

    def common_content 
    @some_instance_variable = :foo 
    end 
end 

지금 @some_instance_variableindex 또는 show 행동에서 렌더링 (파셜 포함) 모든 템플릿에서 액세스 할 수 있습니다 : 예컨대, 필터 전에를 사용하여 여러 작업에 대한 인스턴스 변수를 정의 할 수 있습니다.

+4

이 더 나은 답변입니다! –

+0

Very dry. 좋은! – Red

+0

@Mori 개인/보호 또는 공공 장소에 방법/객체를 배치 할 것인지 결정하는 방법에 대해 어떻게 생각하십니까? ! – Red

관련 문제