While learning Rails, I found this example in the Sam Ruby’s book:
app/controllers/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
Why isn’t the section with redirect_to(@line_item.cart,...) merely replaced by redirect_to(@cart,...) ?
Indeed, @cart is an accessible instance variable.
Are we forced to use @line_item to retrieve cart in this example ?
Is there some sort of nested route involved in this example?
You could simply do a
redirect_to @cartthe example should still work.Try it out. But it should work from my understanding. Maybe the author wanted to be a little bit more expressive in the whose cart he redirects to.