Rails 7.1.x Dynamic Tables

Simple Dynamic Tables without Javascript

I recently learned that Rails 7.1+ has some delightful features that make it easy to render dynamic tables without JavaScript. This is an exploration of using these new features.

This code can be found at: https://github.com/btihen-dev/rails_dynamic_tables

Getting Started

I will create a basic application - using the starting point in the Basic App found at the repo.

In the case I will use the following options:

rails new dynamic_tables -T --main --database=postgresql --javascript=esbuild --css=bootstrap
cd dynamic_tables

Dynamic Tables

Let’s convert the people index view into a table view app/views/people/index.html.erb

# app/views/characters/index.html.erb
<p style="color: green"><%= notice %></p>

<% content_for :title, "Characters" %>

<h1>Characters</h1>

<div class="row justify-content-start">
  <div class="col-4">
    <%= link_to "New", new_character_path, class: "btn btn-primary" %>
  </div>
  <div class="col-8">

  </div>
</div>

<table class="table table-striped table-hover">
  <thead class="sticky-top">
    <tr class="table-primary">

      <th scope="col">
        ID
      </th>
      <th scope="col">
        First Name
      </th>
      <th scope="col">
        Last Name
      </th>
      <th scope="col">
        Gender
      </th>
      <th scope="col">
        Species
      </th>
      <th scope="col">
        Companie-Job
      </th>
    </tr>
  </thead>

  <tbody class="scrollable-table">
    <div id="character">
      <% @characters.each  do |character| %>
        <% jobs = character.jobs %>
        <% companies  = character.companies %>
        <% companies_jobs = companies.zip(jobs) %>
        <tr id="<%= dom_id character %>">
          <th scope="row"><%= link_to "#{character.id}", edit_character_path(character) %></th>
          <td><%= character.first_name %></td>
          <td><%= character.last_name %></td>
          <td><%= character.gender %></td>
          <td><%= character.species.kind %></td>
          <td>
            <ul>
              <% character.person_jobs.each do |person_job| %>
                <li>
                  <%= person_job.company.name %>: <%= person_job.job.role %>
                  <%= person_job.start_date.strftime("%e.%b.%y") %>-<%= person_job.end_date&.strftime("%e.%b.%y") %>
                </li>
              <% end  %>
            </ul>
          </td>
        </tr>
      <% end  %>
    </div>
  </tbody>
</table>

start rails:

bin/rails s

go to: http://localhost:3030/people and be sure this table looks reasonable.

now let’s commit this.

git add .
git commit -m "basic people table added"

Resources

Adding Bootstrap to an existing project

Rails Table Articles

Rails Hotwire

Bill Tihen
Bill Tihen
Developer, Data Enthusiast, Educator and Nature’s Friend

very curious – known to explore knownledge and nature