jbox-web / ajax-datatables-rails

A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app
MIT License
585 stars 228 forks source link

Data method is not called when I go back to the index action. #310

Closed g13ydson closed 5 years ago

g13ydson commented 5 years ago

When accessing the index action of my user controller, the datatable is displayed correctly, but when accessing the view action, for example, and returning to the action index, the date method of the UserDatatable class is not called and nothing is displayed.

I noticed that the javascript file is only called the first time too.

Rails 5.2 ajax-datatables-rails (1.0.0) jquery-datatables (1.10.19.1) jquery-rails (4.3.3)

Here are some excerpts from the code:

class UserDatatable < AjaxDatatablesRails::ActiveRecord
  extend Forwardable

  def_delegator :@view, :link_to
  def_delegator :@view, :edit_user_path

  def initialize(params, opts = {})
    @view = opts[:view_context]
    super
  end

  def view_columns
    @view_columns ||= {
        id:         { source: "User.id" },
        name: { source: "User.name", cond: :like, searchable: true, orderable: true },
        age:  { source: "User.age",  cond: :like },
    }
  end

  def data
   puts "Entered here" #to check if the method was called
    records.map do |record|
      {
        id:         record.id,
        name:       record.name,
        age:  record.age,
        show: link_to("Show", record, class: "btn btn-outline-success my-2 my-sm-0"),
        edit: link_to("Edit", edit_user_path(record), class: "btn btn-outline-warning my-2 my-sm-0"),
        destroy: link_to("Delete", record, class: "btn btn-outline-danger my-2 my-sm-0", method: :delete, data: { confirm: "Are you sure?" }),
        DT_RowId:   record.id,
      }
    end
  end

  def get_raw_records
    User.all
  end
end

UserController

def index
    respond_to do |format|
      format.html
      format.json { render json: UserDatatable.new(params, view_context: view_context) }
    end
  end

users.js

jQuery(document).ready(function() {
  console.log("Entered here");
  $('#users-datatable').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": $('#users-datatable').data('source'),
    "pagingType": "full_numbers",
    "columns": [
      {"data": "id"},
      {"data": "name"},
      {"data": "age"},
      {"data": "show"},
      {"data": "edit"},
      {"data": "destroy"}
    ]
  });
});
g13ydson commented 5 years ago

I solved using turbolinks:load

$(document).on('turbolinks:load', function() {
  $('#users-datatable').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": $('#users-datatable').data('source'),
    "pagingType": "full_numbers",
    "columns": [
      {"data": "id"},
      {"data": "name"},
      {"data": "age"},
      {"data": "show"},
      {"data": "edit"},
      {"data": "destroy"}
    ]
  });
})