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

ordering is not working #300

Closed SpiderEvgn closed 6 years ago

SpiderEvgn commented 6 years ago

Hi, I follow the instructions of 5 steps in Quick Start, below is my code:

=======================================
reference_datatable.rb
=======================================

def view_columns
    @view_columns ||= {
      id: { source: "Reference.id" },
    }
end

def data
    records.map do |record|
      {
        id: record.id,
      }
    end
end

def get_raw_records
    Reference.all
end

=======================================
index.html.erb
=======================================

<div class="table-responsive">
      <table id="references-datatables" data-source="<%= references_path(format: :json) %>" class="table table-striped table-bordered table-hover shadow-sm bg-white rounded">
        <thead>
          <tr>
            <th scope="col"><%= Reference.human_attribute_name('id') %></th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
</div>

<script>
  $(document).ready(function() {
    $("#references-datatables").dataTable({
      "processing": true,
      "serverSide": true,
      "ajax": $("#references-datatables").data("source"),
      "pagingType": "full_numbers",
      "columns": [
        { "data": "id" },
      ]
    });
  });
</script>

=======================================
references_controller.rb
=======================================

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

But I got this error:

ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR:  syntax error at or near "references"
LINE 1: SELECT  "references".* FROM "references" ORDER BY references...
                                                          ^
: SELECT  "references".* FROM "references" ORDER BY references.id ASC LIMIT $1 OFFSET $2):

app/datatables/reference_datatable.rb:17:in `map'
app/datatables/reference_datatable.rb:17:in `data'
app/controllers/admins/references_controller.rb:6:in `block (2 levels) in index'
app/controllers/admins/references_controller.rb:4:in `index'

If I add orderable: false to id, the table shows correctly yet without ordering function.

@view_columns ||= {
      id:    { source: "Reference.id", orderable: false },
}

I totally have no idea how this error happens, I use the same settings for other tables but only this one failed, I hope someone could give me any advise? Thanks a lot.

SpiderEvgn commented 6 years ago

I figured out that its the "reference" name conflict with Rails....