default route in rails

2.9k views Asked by At

I had a doubt when i was writing rails code. In my link_to i used my route order to show my order. So:

<% @orders.each do |order| %>
    <tr>
      <th><%= order.name %></th>
      <th><%= link_to 'Mostra', order %></th>
    </tr>
<% end %>

I saw my rake routes and there was a :

order GET /orders/:id(.:format) orders#show

If i remember right i generated Order resource with scaffolding. However , when i created by hand new resources (not using scaffolding) i had a different route for my resource. For example , i have something like name_resource_show(:id) for the show. This kind of style is good cause i understand that i have to pass the id , if i want to see a specific resource. But in the case before , the case of order , i really don't know how rails is able to understand to use the id of the object order. And also: why i have different routes name? why i have sometimes _path and sometimes (maybe when i generate resource with scaffolding) other things? i would expect something like order_show(:id) and not simply order. how it works?

2

There are 2 answers

0
Pardeep Dhingra On BEST ANSWER

Rails helpers are smart enough to use model object to form url.

<%= link_to 'Mostra', order %> equivalent to <%= link_to 'Mostra', order_path(order) %> and both points to order show page.

This will generate 7 routes for your controller orders.

resources :orders

order GET /orders/:id orders#show

Here order is the helper method it provides to call routes instead of using /orders/:id.

Simply you can use order_path(order) to get route /orders/:id

Similary we get helper for all 7 routes. You can also override the helpers.

Go to below link for more information.

Reference: http://guides.rubyonrails.org/routing.html

0
sscirrus On

First, I recommend following the Rails conventions on routes (see the main reference article here).

Here are answers to your questions in order.

  • The route you got from rake routes makes sense in the following way. Look at the URL (orders/:id). Within all of your orders, the :id passed specifies which one to look at. The GET nature of the request indicates you are getting the data on that record, i.e. that it is a SHOW action.
  • Rails understands where the ID is because of how the routes are structured. If you had order GET /orders/:year/:id in routes, then Rails will know to look for the third parameter for the ID it needs.
  • The two for accessing routes options are _path and _url (see here for details), but there are some alternatives explained in the main reference article I linked at top.
  • You can still use the explicit route, but the order option is simply a bit of sugar Rails offers to make things easier to read.