link_to block inside a each do loop not working

561 views Asked by At

I'm trying to render a table whose columns are subreddit titles and have links to each subreddit. However, this doesn't generate the link. I want to make the entire row a link, not a specific cell. What's the problem?

    <% @subreddits.each do |subreddit| %>
      <tr>
        <%= link_to subreddit do %>
          <td><%= something else %></td>
          <td><%= subreddit.title %></td>
        <% end %>
      </tr>
    <% end %>
1

There are 1 answers

0
Justin On

You are wrapping the link around the <td> element. Wrap the <td> around the link.

<% @subreddits.each do |subreddit| %>
  <tr>
    <td>
      <%= link_to(subreddit.title, subreddit) %>
    </td>
  </tr>
<% end %>

If you are wanting to make the entire <td> a link, you'll have to use the above code plus something like this:

https://stackoverflow.com/a/6459846/2456549


Update

It looks like you updated your question to add additional <td>s. It looks like you are now wanting to make your <tr> a link. The best way to accomplish this is probably to just use JavaScript. See the link below for the solution. I would add CSS also so the <tr> has a pointed cursor, for improved UX.

how to make a whole row in a table clickable as a link?


I've went ahead and added the full solution here, without the need for dependencies like jQuery, granted, it is written in ES6, so change const to var if you need to. Please note, it hasn't been tested.

<tr class="cursor-pointer"
  data-behavior="clickable-row"
  data-url="<%= subreddit_url(subreddit) %>">
  <td><%= something else %></td>
  <td><%= subreddit.title %></td>
</tr>

const clickableRows = document.querySelectorAll('[data-behavior=clickable-row]');

clickableRows.addEventListener('click', event => {
  window.location = event.currentTarget.dataset.url;
});

.cursor-pointer { cursor: pointer; }