small medium large xlarge

Generic-user-small
16 Jan 2009, 23:29
Ron Nollen (2 posts)

From the “Building an Application” section of “Agile Web Development with Rails, Third Edition”.

This should be an easy one to answer… the products controller contains a create method which in turn has the statement “format.html {redirect_to(@product)}” How does rails know to redirect me to the “show” page?

I understand that by convention the POST call (from new) invokes the create action in the controller, but how does the redirect_to(@product) know which page to take me to?

Thanks for your help, Ron.

Generic-user-small
20 Jan 2009, 18:52
Chap Ambrose (2 posts)

I think the controller sees it as a GET request, so it forwards it to the show action.

Picket01_pragsmall
21 Jan 2009, 07:49
Dary Merckens (2 posts)

It’s a combination of the Rails methods redirect_to, url_for and polymorphic_url (which used to be part of the simply_helpful plugin). When you give redirect_to an object it calls redirect_to_full_url(url_for(options), status) because the object isn’t an explicit URL, a String, or the :back symbol. url_for, when given an object, calls polymorphic_url(options) polymorphic_url is a really nifty helper method that returns the appropriate route based on the object’s class. Also, if it’s an ActiveRecord object, it returns a different URL depending on whether the object is a new record or not. So in the redirect_to(@product) from the create method, polymorphic_url sees that it has an instance of the Product class, so it’s either going to return products_path (the index action) or product_path(@product) (the show action). Since this is a new record, it returns the latter, redirecting you to the show page of your newly created product.

You must be logged in to comment