2016-09-13 1 views
0

다음 컨트롤러 Foobar 리소스를 갖는리소스 컨트롤러`# create` 메소드에서 인스턴스 변수를 설정해야합니까?

class FoobarController < ApplicationController 
    def new 
    @foobar = Foobar.new(baz: params[:baz]) 
    @foobar.build_data 
    end 

    def create 
    @foobar = Foobar.new(foobar_params) 
    respond_with(@foobar) 
    end 

    # ... 
end 

그것은 #create 방법 가변 인스턴스 @foobar을 설정할 필요가있다? 쓸 수 없습니까?

def create 
    Foobar.new(foobar_params).tap &method(:respond_with) 
end 

?

답변

2

응답하는 콘텐츠 유형에 따라 다릅니다. docsrespond_with으로 전화하면 정확히 어떻게되는지 설명합니다. 귀하의 경우, create 행동, respond_with는 컨트롤러에 respond_to 호출에 HTML 이외의 형식을 지정하지 않은 당신을 가정, 다음과 동일하다 :

respond_to do |format| 
    if @foobar.save 
    flash[:notice] = 'Foobar was successfully created.' 
    format.html { redirect_to(@foobar) } 
    else 
    format.html { render action: "new" } 
    end 
end 

유일한 경우 어디 @foobar 인스턴스 변수 유효성 검사 오류가 있고 new.html 템플릿에 @foobar이 포함되어 있으면 필요합니다. foobar_params이 항상 유효한 경우 respond_with은 항상 show 작업으로 리디렉션하여 응답하므로 인스턴스 변수는 필요하지 않습니다.

관련 문제