The idea to write this blog came out during my Mod2 Project at Flatiron School, during which my Partner Austin Buhler and I decided to create a Fantasy Football Lineup Optimizer. We built a large pool of NFL Players, and very quickly I realized we had a need to sort and filter this table by multiple attributes, as well as search the table for certain values. Unfortunately, I had no idea how to do this. So began my dive into the world of Tables, HTML, and Rails.

Creating Tables in HTML View Pages

We’ll start by defining our table of NFL Players. Each player has a name attributes, position attribute, and an aggregate ranking.

#views/players/index.html.erb

<h1>Players List</h1>
<table>
  <tr>
    <th>Player Name </th>              <-- Each of these
    <th>Position </th>                      is a column header
    <th>Avg. Ranking </th>
  </tr>
 <% @players.each do |player| %>
  <tr>
    <td><%= player.name%></td>         <-- Each of these adds
    <td><%=player.position %></td><td>     data to the corresponding
    <td><%=player.avg_ranking %></td>      column in the same row
  </tr>
  <% end %>
 </table>

This is just a combination of HTML tags and rails methods:

  • The <table> tag defines an HTML table.
  • Each table row is defined with a <tr> tag
  • Each table header is defined with a <th> tag
  • Each table data/cell is defined with a <td> tag
  • The ‘<%=’ and ‘%>’ wrappers denote Ruby code

Sorting

Now that our Table is set up, we need to add some functionality to make it easily sortable.

The first thing we’ll do is make the table headings links, so we’ll need to add link_to before each header cell’s text. The page we want each link to go to is the same page we’re on but with different query string parameters. To do that we just need to specify a hash as the second parameter to link_to.

#searching #ruby-on-rails #programming #rails #sorting

Using Rails and HTML to View, Sort, and Search Tables.
1.35 GEEK