redirect_to in controller

30 views
Skip to first unread message

PC Leung

unread,
Nov 14, 2013, 6:44:47 AM11/14/13
to hk...@googlegroups.com
Hi All

when 'create' procedure is called in line_items_controller.rb, it will redirect to @line_item.cart.

Actually, I find  ../views/carts/show.html.erb is called.
but ../views/line_items/show.html.erb is not used.

why "@line_item.cart" is mapped to ../carts/show.html.erb ?

Thanks 

-------------

line_items_controller.rb

def create
product = Product.find(params[:product_id]) @line_item = @cart.line_items.build(product: product)

respond_to do |format| if @line_item.save

format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }

format.json { render action: 'show', status: :created, location: @line_item } 

Matthew Rudy Jacobs

unread,
Nov 14, 2013, 7:09:18 AM11/14/13
to hk...@googlegroups.com
@PC
redirecting_to *redirects* to a new url.

If you check the URL bar on your browser, it should say /cars/1

So actually, the rendering is taking place in the CartsController.

Why not run `tail -f log/development.log`, and see what is actually happening?


--
You received this message because you are subscribed to the Google Groups "Hong Kong Ruby on Rails" group.
To unsubscribe from this group and stop receiving emails from it, send an email to hkror+un...@googlegroups.com.
To post to this group, send email to hk...@googlegroups.com.
Visit this group at http://groups.google.com/group/hkror.
For more options, visit https://groups.google.com/groups/opt_out.

PC Leung

unread,
Nov 14, 2013, 9:53:17 AM11/14/13
to hk...@googlegroups.com
Hi Mattew

In the log, I find it goes from 

Processing by LineItemsController@create as HTML
..
..
Processing by CartsController#show as HTML

why "redirect_to @line_item.cart" can do this?

Thanks

PC Leung

unread,
Nov 14, 2013, 10:20:12 AM11/14/13
to hk...@googlegroups.com
is it correct ?

because @line_item.cart contains a number, say '16',
then it goes to #show. 

since it is under CartsController
thus CartsController#show is called. 

I have replaced @line_item.cart with carts_path. It goes to CartsController#index.

Matt U

unread,
Nov 14, 2013, 6:51:45 AM11/14/13
to hk...@googlegroups.com
Hi PC,

The short version of what's going on, is that you're telling it to redirect to an instance of 'Cart', so it is redirecting to cart_url(@line_item.cart), which would be invoking CartsController#show - and hence the view for cart is rendered.

This is normally the desired behaviour, so perhaps redirecting to the cart isn't exactly the behaviour that you are after?

Cheers,
Matt

Sent from my iPhone
--

PC Leung

unread,
Nov 14, 2013, 9:10:44 PM11/14/13
to hk...@googlegroups.com
Thanks Matt. I check and learn how it works only.
Reply all
Reply to author
Forward
0 new messages