的支架產生像這樣的新的動作:Rails中新控制器操作的目的是什麼?
def new
@product = Product.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @product }
end
end
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to(@product, :notice => 'Product was successfully created.') }
format.xml { render :xml => @product, :status => :created, :location => @product }
else
format.html { render :action => "new" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
end
和視圖呈現的部分,命名form
。由於new
窗體呈現與創建新產品的動作集相同,因此@product
的目的是什麼?我看到create
動作也會實例化一個新對象。它是否僅用於使您可以將表單綁定到對象,以便所有內容都從行爲到正確行爲?
是的,但我不明白這有什麼好處。當'create'動作被調用時,它重新定義'@ product'。 – Geo 2011-03-09 17:04:22
我剛剛編輯了答案,所以我認爲你可能沒有看到它。 @產品的範圍在動作(或請求)內。其狀態不會保留在下一個請求中,即創建操作。 – 2011-03-09 17:05:52
是的,當行動結束時'@ product'消失是有道理的,但爲什麼要使用它呢?爲什麼不使用與模型無關的表單?對我來說,這似乎只是對內存的浪費。我相信這一定有一個潛在的目的,但我還沒有看到它。 – Geo 2011-03-09 17:10:39