Search code examples
ruby-on-railsruby-on-rails-4routesscaffolding

default route in rails


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?


Solution

  • 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