Reputation: 43
I am a beginner in Ruby on Rails and following The rails tutorial by Michael Hartl's. In chapter 2, I am stuck at the following code in the part where link_to
has been used. How does link_to knows which link_to point to, when we haven't explicitly written any URL?
<h1>Listing users</h1>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, confirm: 'Are you sure?',
method: :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New User', new_user_path %>
Thanks everyone. Somehow I can't comment because JavaScript has been failed to load. Thanks amalrik maia for providing the link.
Solution: http://guides.rubyonrails.org/routing.html
2.3 Path and URL Helpers
Creating a resourceful route will also expose a number of helpers to the controllers in your application.
In the case of resources :photos:
photos_path returns /photos
new_photo_path returns /photos/new
edit_photo_path(:id) returns /photos/:id/edit (for instance, edit_photo_path(10) returns /photos/10/edit)
photo_path(:id) returns /photos/:id (for instance, photo_path(10) returns /photos/10)
Each of these helpers has a corresponding _url helper (such as photos_url) which returns the same path prefixed with the current host, port and path prefix.
Upvotes: 1
Views: 613
Reputation: 468
<h1>Listing users</h1>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, confirm: 'Are you sure?',
method: :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New User', new_user_path %>
link_to
doesn't know anything about paths or URLs.
The URLs are generated by Rails' routing helpers like:
edit_user_path()
new_user_path
To see the complete listing of routes go to your terminal and type:
bundle exec rake routes
See the routing documentation for more information.
Upvotes: 1
Reputation: 4453
You have a syntax error. This:
<%= link to 'New User', new user path %>
Should be:
<%= link_to 'New User', new_user_path %>
The paths are rails 'helpers.' Start here: http://guides.rubyonrails.org/routing.html
They are basically shortcut methods that point to a particular url. These urls are defined in your routes.rb file.
Upvotes: 4