Reputation: 25062
I am trying to make a row in a table link to the edit page. I know the links are being created, because I can print them out. I am close, but am missing something important. What do I change to make the link work properly?
<h1>Scouts</h1>
<p><%= button_to "Add a new Scout", new_scout_path, :method => :get %></p>
<div class="message-board">
<table>
<tr>
<th>Name</th>
<th>Rank</th>
<th>Advancement Date</th>
<th>Age</th>
</tr>
<% @scouts.each do |scout| %>
<tr <% link_to edit_scout_path(scout) %> >
<td><%= scout.name %></td>
<td><%= scout.rank %></td>
<td><%= scout.advancement %></td>
<td><%= scout.age %></td>
</tr>
<% end %>
</table>
</div>
Upvotes: 40
Views: 27173
Reputation: 35731
This doesn't answer your question, but it provides a solution to the problem you are likely really after: just add an edit link into a cell, rather than on the table row because having a link on the table row itself may lead to expected results for users. If they are clicking on it, they might not want to be led to an edit link.
Like my grandpa used to say: KISS - Keep It Simple Stupid
<% @scouts.each do |scout| %>
<tr>
<!-- Simply edit the scout -->
<td> <%= link_to edit_scout_path(scout), "Edit Scout" %> </td>
<td><%= scout.name %></td>
<td><%= scout.rank %></td>
<td><%= scout.advancement %></td>
<td><%= scout.age %></td>
</tr>
Upvotes: -1
Reputation: 1
Here is my take to make those links, remote: true
$("tr[data-link]").click(function () {
$.ajax({
url: this.getAttribute('data-link'),
dataType: "script",
type: "GET"
});
event.preventDefault();
});
Upvotes: 0
Reputation: 107738
As Robin said, that's invalid HTML. You probably shouldn't do that.
I personally would put an onclick
event on the tr
using jQuery. The tr
element would look like this:
<tr data-link="<%= edit_scout_path(scout) %>">
...
</tr>
And then the associated JavaScript (placed in a file such as app/assets/javascripts/scouts.js
) would be something like this:
$("tr[data-link]").click(function() {
window.location = $(this).data("link")
})
This would make all tr
elements that have a data-link
attribute act as if they were URLs in the most unobtrusive way I can think possible.
Upvotes: 76
Reputation: 346
I am new on rails and I have the same problem and use the Ryan's advise with some changes that are following -
$("tr").click(function() {
window.location = $(this).data("link")
})
You have to use $(this).
Upvotes: 5