Using Rails' resources
directive, I have created a set of routes for a controller (contacts
). I'm now editing the default views they come with to include some of my own content. However, the link_to
method is failing, telling me that I'm missing a required parameter.
No route matches
{:action => 'show', :controller => 'contacts', :id => nil}
missing required keys[:id]
It's obvious why this is happening - the link_to
method is not being supplied with an ID, instead it's getting nil. However, the code I'm using matches the documentation for link_to
.
This is the view in question:
<% @contacts.each do |contact| %>
<tr>
<td><%= contact.first %></td>
<td><%= contact.last %></td>
<td><%= contact.title %></td>
<td><%= contact.city %></td>
<td><%= contact.phone %></td>
<td><%= contact.email %></td>
<td><%= link_to 'Show', contact %></td>
<td><%= link_to 'Edit', edit_contact_path(contact) %></td>
<td><%= link_to 'Delete', contact.id, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
@contacts
is a set of contacts returned from the controller. The line that sets that is:@contacts = Contact.select("title, first, last, city, phone, email") .where("created_by" => @current_user.id)
The relevant content of the routes.rb file is simply
resources :contacts
.
The documentation states:
Because it relies on url_for, link_to supports both older-style controller/action/id arguments and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base your application on resources and use [...]
link_to "Profile", @profile
This appears to be what I'm using with link_to 'Show', contact
.
- Why is the ID not getting passed to
link_to
? - What can I do to remedy this?