DataTables

#82 DataTables
5/29/2017

Summary

The DataTables Javascript library creates a powerful display of your application's data. Some of the features include pagination, server side processing, sorting and search.
11
rails javascript tables view 15:55 min

Summary

Gemfilegem 'rails-assets-jquery', source: 'https://rails-assets.org'
gem 'rails-assets-datatables', source: 'https://rails-assets.org'
gem 'kaminari'
index.html.erb<%= content_tag :table, role: :datatable, data: { url: users_path(format: :json)} do %>
  <thead>...</thead>
  <tbody></tbody>
<% end %>
users_controller.rb  def index
    respond_to do |format|
      format.html
      format.json { render json: UsersDatatable.new(view_context) }
    end
  end
app/datatables/application_datatable.rbclass ApplicationDatatable
  delegate :params, to: :@view
  delegate :link_to, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      recordsTotal: count,
      recordsFiltered: total_entries,
      data: data
    }
  end


private

  def page
    params[:start].to_i / per_page + 1
  end

  def per_page
    params[:length].to_i > 0 ? params[:length].to_i : 10
  end

  def sort_column
    columns[params[:order]['0'][:column].to_i]
  end

  def sort_direction
    params[:order]['0'][:dir] == "desc" ? "desc" : "asc"
  end
end
app/datatables/user_datatable.rbclass UsersDatatable < ApplicationDatatable
  delegate :edit_user_path, to: :@view

  private

  def data
    users.map do |user|
      [].tap do |column|
        column << user.first_name
        column << user.last_name
        column << user.email
        column << user.phone_number

        links = []
        links << link_to('Show', user)
        links << link_to('Edit', edit_user_path(user))
        links << link_to('Destroy', user, method: :delete, data: { confirm: 'Are you sure?' })
        column << links.join(' | ')
      end
    end
  end

  def count
    User.count
  end

  def total_entries
    users.total_count
    # will_paginate
    # users.total_entries
  end

  def users
    @users ||= fetch_users
  end

  def fetch_users
    search_string = []
    columns.each do |term|
      search_string << "#{term} like :search"
    end

    # will_paginate
    # users = User.page(page).per_page(per_page)
    users = User.order("#{sort_column} #{sort_direction}")
    users = users.page(page).per(per_page)
    users = users.where(search_string.join(' or '), search: "%#{params[:search][:value]}%")
  end

  def columns
    %w(first_name last_name email phone_number)
  end
end
application.js//= require jquery
//= require datatables

...

$(document).on('turbolinks:load', function(){
  $("table[role='datatable']").each(function(){
    $(this).DataTable({
      processing: true,
      serverSide: true,
      ajax: $(this).data('url')
    });
  });  
})
application.css *= require datatables
 *
 * For bootstrap support
 * require datatables/dataTables.bootstrap
 * 


00000000000000000000000000000000?d=mm&f=y&s=64
frank004 said 5 months ago:

can you make a part 2 of this where you add style to the content and links. Thank you

635114?v=3&s=64
kobaltz said 5 months ago:

You should be able to simply add a class attribute to the link_to methods as you normally would to get the styling.

00000000000000000000000000000000?d=mm&f=y&s=64
frank004 said 5 months ago:

I like to keep my markup and style out of the controller and Models.

In this example Im adding 2 Data base Table column to one  View Table with the Project name as the column and the manager as a small span. How can I  recreate this with the json technic.

Example Data:

Table

Project | Date | Actions
Project Name, project manager  | 11/20/2011 | edit, change status action, delete

<tr>

    <td class="cell_stuff" ><%=link_to project. project, class: "stuff_link"%>

     <span class="stuff"> <%= project.manager.full_name%> </span>

</td>


635114?v=3&s=64
kobaltz said 5 months ago:

I see, keep in mind that the UsersDatatable is its own class and nor really part of the model or controller.

You could extract out the contents of the data method into its own class which I would probably do for larger tables.

As far as the classes on the td tags, that should be possible to do with their API. I'll look into it.

00000000000000000000000000000000?d=mm&f=y&s=64
frank004 said 5 months ago:

Perfect. will check that out.

FYI. Check your site permisión Display UI view. I can see the Delete Edit on your comment.

635114?v=3&s=64
kobaltz said 5 months ago:

Thanks for the heads up. It wouldn't work since I'm doing server side authorization, but definitely shouldn't display.

179822?v=3&s=64
brandoncordell said 5 months ago:

Would it make sense to memoize the User.count call? I'm not super familiar with memoization, so I'm not sure whether it would benefit this specific situation.

635114?v=3&s=64
kobaltz said 5 months ago:

Not really since it isn't being used elsewhere in the class. Keep in mind that the memorization is only valid for the lifecycle of the request and any further requests would no longer have the calculations stored. 

00000000000000000000000000000000?d=mm&f=y&s=64
bud said 3 months ago:

How do you deal with enums in this setup?  Say I have an integer column and I use enums in it - 0 is "no" and 1 is "yes".  How do you filter for the strings rather than the integers within the table?

635114?v=3&s=64
kobaltz said 3 months ago:

Great question. It really depends on the complexity to which you've modified the datatables. If you are using server side data and a full text engine, then I would store the 'yes' and 'no' values as part of the indexed data.

If you're using Rails 5.1.x then you could also use a virtual attribute to search on instead of the integer column.

00000000000000000000000000000000?d=mm&f=y&s=64
bud said 3 months ago:

Thanks for the quick reply.  I am indeed using Rails 5.1.x.  Do you have an example in the context of your demo in how I could accomplish this with virtual attributes?  Never heard of these and am reading about them now.

00000000000000000000000000000000?d=mm&f=y&s=64
bud said 3 months ago:

Thanks!  Very useful.  I understand the concept, but I'm still not sure what the best approach would be to use virtual attributes against an integer column and somehow extract a string from that.  Would I need to define a virtual attribute for each integer that I have mapped as an enum?  In my case I have up to 10 enums in some columns.

00000000000000000000000000000000?d=mm&f=y&s=64
bud said 2 months ago:

Just a fyi - I ended up creating my own custom select boxes that handle filtering for my enum columns.

17704716?v=4&s=64
rhodium45 said 4 days ago:

Hey,

how can I add links to the <td> tags/cells directly, like <td><%= link_to product.name, product %></td>

Cheers,

Drilon

17704716?v=4&s=64
rhodium45 said 4 days ago:

Hey guys,

this was way easier than I initially thought. Instead of having column << product.name, it just had to be column << link_to(product.name, product).


Cheers,

Drilon

Login to Comment