在学习Rails时,我在Sam Ruby的书中找到了这个例子:
应用/控制器/ 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
来检索购物车?
答案 0 :(得分:1)
此示例中是否涉及某种嵌套路由?
你可以简单地做一个redirect_to @cart
示例应该仍然有效。
试一试。但它应该从我的理解中发挥作用。也许作者想要在他重定向到的购物车中表现得更有表现力。
答案 1 :(得分:1)
这是我们必须假设作者试图传达的时代,
“保存此line_item后,转到购物车哪个有线__>” =>可读性。
好的代码应该提供两件事,无论如何,
我从经验和现实中意识到了他们的必要性。 (不是出书)
获得正确的输出后可以考虑优化。
如果我错了,请纠正我。