在学习 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
在这个例子中我们是否被迫使用来检索购物车?