Neil Neil - 3 months ago 63
Ruby Question

Sort table data by columns in rails with bootstrap

Edit: I would prefer to using bootstrap for this functionality if possible since I have bootstrap in my project. It seems like I might just be missing something to utilize bootstrap's javascript within my rails project.

When the column name is clicked, the table should sort the data by that column name. Below is the table:

enter image description here

I attempted to sort the data with bootstrap, following the examples shown at this website, but it wasn't working for me. What am I missing?

Relevant gems in my Gemfile:

#Gemfile
gem 'bootstrap-sass'
gem 'autoprefixer-rails'


CSS:

#app/assets/stylesheets/application.css.scss
@import "bootstrap-sprockets";
@import "bootstrap";
/*
*= require_tree .
*= require_self
*/


Javascript:

#app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .


View displaying records:

#app/views/index.html.erb
<h4>Listing Users</h4>

<table class=" table table-striped" data-sort-name="name" data-sort-order="desc">
<thead>
<tr>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="age" data-sortable="true">Age</th>
</tr>
</thead>

<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.age %></td>
</tr>
<% end %>
</tbody>
</table>

<br>

<%= link_to 'New User', new_user_path %>

Answer

Thanks to a lot of feedback from Hunter Stevens. Best option I found for me was to use sorttable.js. Process I used was the following:

  1. Add gem 'jquery-turbolinks' to your Gemfile to fix turbolink javascript issue and bundle install
  2. Add jquery.turbolinks to javascript manifest file:

    #app/assets/javascripts/application.js
    //= require jquery
    //= require jquery_ujs
    //= require jquery.turbolinks
    //= require bootstrap-sprockets
    //= require turbolinks
    //= require_tree .
    
  3. Go here to copy the code for sorttable.js

  4. Create js file at: app/assets/javascripts/shared/<whatever_you_want_to_call_it>.js. Use $(document).ready as shown to fix turbo link problem. Specify an IIFE (optional) then paste the vendor code within that IIFE:

    $(document).ready(function(){
      (function vendorTableSorter(){ 
        /* paste all the vendor code here */
      }());
    });// end document.ready
    
  5. Then, simply add the class sortable to your table,which makes all the columns sortable:

    <table class=" table table-striped sortable">
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
    
     <tbody>
       <% @users.each do |user| %>
         <tr>
          <td><%= user.name %></td>
          <td><%= user.age %></td>
        </tr>
       <% end %>
     </tbody>
    

Comments