2014-07-11 4 views
2

html과 json의 두 가지 형식으로 동일한 루트에 응답하는 컨트롤러 작업이 있습니다. 그러나 HTML 응답을 실행하는 코드는 는 지금은html 또는 json에 대한 동일한 컨트롤러 동작의 다른 코드

def index 
    result_html = ... 
    result_json = ... 
    respond_to |format| 
    format.html 
    format.json { result = result_json.limit(10) } 
    end 
end 

같은 것을하고 난

def index.html 
    result_html ... 
end 

및처럼하고 싶은 .. JSON 응답에 대한보다 완전히 다른

def index.json 
    result_json ... 
end 

어떻게 구성하는 것이 가장 좋을까요?

답변

5

다음과 같이 표시 될 수 있습니다.

def index 
    respond_to |format| 
    format.html { index_html} 
    format.json { index_json } 
    end 
end 

def index_html 
    ... 
end 
def index_json 
    ... 
end 
1

request.format.symbol으로 서식을 테스트 한 다음 when :json으로 전화를 걸면 json 동작이 호출되거나 when :html은 html 동작을 호출 할 수 있습니다.