What steps should be taken to set up the datatable to sort records in descending order based on the creation date?

In my Rails application, I am utilizing the Datatable plugin to display data on the User index page. The first column in the index page is the created_at field, which displays dates like Mon, 17-Oct-16. I want to sort this column in descending order based on this date format. How can I achieve that? Here's what I have attempted so far, but it has not yielded the desired results.

<script type="text/javascript">
  $(document).ready(function() {
    var dataTable = $('#reg_req_data_table').dataTable({
      "order": [[ 1, "desc" ]],
       'aoColumnDefs': [{
       'bSortable': false      
    }],
    "bLengthChange": false,
    "sDom": '<"top"pfl>rt<"bottom"i><"clear">'
      });
  });
</script>

Answer №1

Discover how to comply with Rails conventions and manage sorting in a ruby class before returning the data as json to DataTables. If you're dealing with a large volume of records, it's best practice to opt for server-side processing over client-side processing as it offers better performance (the example below demonstrates server-side processing):

The user#index action should be:

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

Create a subfolder named datatables within your app folder and include this .rb file:

#app/datatables/users_datatable.rb   Note that it's named users_datatable! Rails will automatically determine the correct class lookup path because of this.
class UsersDatatable
  delegate :params, :h, :link_to, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: User.count,
      iTotalDisplayRecords: users.total_entries,
      aaData: data
    }
  end

private

  def data
    users.map do |user|
      [
        user.created_at.strftime("%d-%b-%y")
      ]
    end
  end

  def users
    @users ||= fetch_users
  end

  def fetch_users
    users = User.all.order("created_at DESC")
    users = users.page(page).per_page(per_page)
    if params[:search].present? && params[:search]["value"].present?
      users = users.where("email like :search", search: "#{params[:search]["value"]}%")
    users
  end

  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 = %w[created_at ]
    columns[params[:order]["0"]["column"].to_i]
  end

  def sort_direction
    params[:order]["0"]["dir"] == "desc" ? "desc" : "asc"
  end
end

Your corresponding users view index.html.erb should look like this:

<div class='table-responsive'>
  <table id='reg_req_data_table' data-source="<%= users_path(params.merge!(format: :json).deep_symbolize_keys)%>">
  <thead>
    <tr>
       <th>Created On:</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $('#reg_req_data_table').DataTable({
       "serverSide": true,
       "ajax": {url: '<%= users_path(params.merge!(format: :json).deep_symbolize_keys)%>', type: "POST"},
       "processing": true
    }),
  });
</script>

Take note of the empty table body tags. With server-side processing, DataTables retrieves information via json, which is provided by the UsersDatatable class.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it possible for the EXPRESS+EJS template to access CONFIG without explicitly passing it when rendering?

Currently exploring my knowledge of node.js alongside express and the ejs template. As I delved into some code, I stumbled upon the fact that they were able to invoke config in the template without explicitly passing it as a variable during rendering. You ...

When the nesting in AngularJS ui-router becomes overwhelming

I've been in the process of refactoring a large application at work, and I've noticed significant similarities between different parts of the app that make me think nesting routes could be beneficial. However, as I continue to nest more and more, ...

The statement ""x=x || 4" will result in a `ReferenceError: x is not defined` because the

What is the reason behind receiving a ReferenceError: x is not defined error when using x = x || 4 or even x=(x||5), while var x = x || 4 operates as intended? ...

It appears that using "object[prop]" as a name attribute does not function properly in HTML

After using console.log on the req.body I received this output: [Object: null prototype] { 'shoe[name]': 'Shoe Name', 'shoe[description]': '', 'shoe[pictures]': '', 'shoe[collections] ...

Need Root Directories in Browserify and Using NPM (eliminating the constant use of '../../../..' in both cases)

Despite my extensive search for a solution to this issue, I have been unsuccessful so far – even after referring to the amazing gist on improving local require paths and thoroughly reading the Browserify handbook section on Avoiding ../../../../... I am ...

There are times when the `window.location.replace` function does not

I have implemented a Bootstrap Dropdown feature that allows users to select a language for site translation, append the URL with the selected language, and then reload the page. Initially, it works well for the first set of translations like en|es. Howeve ...

My JavaScript seems to be having an issue with .className - can anyone help me troubleshoot

I'm currently working on a navigation menu, and my objective is to have the class change to .nav-link-active when a link is clicked, while also reverting the current .nav-link-active back to .nav-link. Here's the code snippet I am using: <he ...

THREE.JS: Organizing Objects into Multiple Groups

Currently, I am in the process of learning THREE.js and attempting to create a playable Rubik's cube. My goal is to rotate a face as a whole instead of manipulating each cube individually. I have tried placing the cubes within a THREE.Group, but the ...

Adjusting the background color of a MuiList within a React Material-UI Select component

Looking to customize the background color of the MuiList in a react material-ui Select component without affecting other elements. Specifically targeting the Select element with the name 'first'. Despite setting className and trying different cl ...

Out of nowhere, jQuery suddenly fails to recognize that my checkbox has been selected

http://pastebin.com/r30Wfvi3 Out of the blue, all that functionality suddenly ceased. var showMyLocation = document.createElement('input'); showMyLocation.type = "checkbox"; showMyLocation.className = "checkboxForRange"; showMyLocation.id = "sh ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

How can you show the default calendar for a specific month and year in a Vue3 datepicker?

I've been utilizing the @vuepic/vue3datepicker component, which automatically shows the days of the current month when integrated in my project: <template> <VueDatePicker v-model="date" inline></VueDatePicker> </templ ...

Arranging data in CodeIgniter Pagination

After successfully implementing Pagination in CI using a tutorial I found online, I decided to tackle Sorting on my own. However, I encountered an issue where the pagination links did not include the necessary URI Segments for "sortfield" and "sortorder," ...

I'm experiencing difficulties in installing dependencies for my project through npm, as it keeps showing an error

Recently, I decided to delve into the world of HTML5 and javascript games by running a browser game from Github. The game that caught my eye is called BrowserQuest, and you can find it on Github. A hiccup arose while using npm debug: 237 error 404 Not ...

Is it advisable to use npm devDependencies in a production environment?

While reviewing the package.json file for one of our products at work, I noticed that the SDK uses socket.io for a crucial function even though socket.io-client is listed as a devDependency. Despite this discrepancy, the SDK works flawlessly for our clie ...

The "self" variable in the Node.js prototype object fails to retain the correct context for the callback function

Although I have experience as a developer, I am new to Java Script and Node.js. I have searched through various examples and Stack Overflow answers, but I couldn't find a simple and complete example of a prototypical class with correct 'self&apos ...

Fresh Redux shop in stealth mode

I am managing a Single Page Application using React and Redux. Some customers have expressed interest in keeping two separate instances open with distinct credentials (one in normal view and one in incognito mode on Chrome). As both instances can access t ...

Looking for a speedy solution with a [PHP function] that needs to be converted to a [JavaScript function

Looking for a quick favor - can anyone help me out with this: static function make_url_safe($z){ $z = strtolower($z); $z = preg_replace('/[^a-zA-Z0-9\s] /i', '', $z); $z = str_ireplace(' ', '-', $z) ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...