0
0

More than 1 year has passed since last update.

Railsのテーブル要素にリンクをつけた

Last updated at Posted at 2021-10-18

tableのtr(行ごと)にリンクを貼る

viewにリンクを追加

index.html.erb
<tbody class="institution_index_table_tbody">
  <% @institution.each do |institution| %>
    <%# data-hrefにリンク先を記述する %> 
    <tr class="institution_index_tbody_tr" data-href="/institutions/<%= institution.id%>">
      <td class="institution_index_td name_td"><%= institution.name %></td>
      <td class="institution_index_td postcode_td"><%= institution.postcode %></td>
      <td class="institution_index_td address_td"><%= institution.address %></td>
      <td class="institution_index_td intro_td"><%= institution.introduction%></td>
    </tr>
  <% end %>
</tbody>

jsの設定

app/javascript/packs/institutions.js
jQuery(document).on("turbolinks:load", function() {
  $(".institution_index_tbody_tr").on('click', function() {
      window.location = $(this).data("href");
  });
});

institution_index_tbody_trクラスをクリックしたら、data-hrefのリンクに遷移する。

app/javascript/packs/application.js
import "packs/institutions.js"

tableのtd(セルごと)にリンクを貼る

ほとんど一緒

viewにリンクを追加

index.html.erb
<tbody class="institution_index_table_tbody">
  <% @institution.each do |institution| %>
    <tr class="institution_index_tbody_tr">
      <td class="institution_index_td name_td" data-href="/institutions/<%= institution.id%>"><%= institution.name %></td>
      <td class="institution_index_td postcode_td"><%= institution.postcode %></td>
      <td class="institution_index_td address_td"><%= institution.address %></td>
      <td class="institution_index_td intro_td"><%= institution.introduction%></td>
    </tr>
  <% end %>
</tbody>

jsの設定

app/javascript/packs/institutions.js
jQuery(document).on("turbolinks:load", function() {
  $(".name_td").on('click', function() {
      window.location = $(this).data("href");
  });
});

// institution_index_tdにリンク先を設定しない<td>をクリックするとエラーになる
jQuery(document).on("turbolinks:load", function() {
  $(".institution_index_td").on('click', function() {
      window.location = $(this).data("href");
  });
});
app/javascript/packs/application.js
import "packs/institutions.js"

参考資料

railsでテーブル要素の一つ一つにリンクを貼る方法
how to make a whole row in a table clickable as a link?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0