在學習Rails的,我找到了山姆紅寶石的書這個例子:難道我們不能有更簡單的redirect_to參數嗎?
應用程序/控制器/ line_items_controller.rb
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build
@line_item.product = product
respond_to do |format|
if @line_item.save
# this following line is strange for me
format.html { redirect_to(@line_item.cart, :notice => 'Line item was successfully created.') }
format.xml { render :xml => @line_item, :status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors,
:status => :unprocessable_entity }
end
end
end
爲什麼不與redirect_to(@line_item.cart,...)
部分由redirect_to(@cart,...)
僅僅更換?
確實,@cart是一個可訪問的實例變量。
在這個例子中,我們是否被迫使用@line_item
來檢索購物車?
否這個例子中沒有涉及嵌套路由。作者寫道:「創建訂單項後,我們希望將您重定向到購物車,而不是返回到訂單項本身。由於行對象知道如何查找購物車對象,因此我們只需添加.cart到方法調用「。所以,像這樣長的精確度,我想知道這種做法是否是這樣:)。 – Mik378
不,這不是唯一的方法。實際上,路由幫助器只會查看傳遞的對象(@cart)並將其與其路由進行匹配。因此,如果路徑文件具有「資源:購物車」,它會將其與show_cart路徑匹配。不知道爲什麼作者決定這樣寫。 – Tigraine
我完全同意你的看法,我不明白這個精度的目標。謝謝 :) – Mik378