tessad
tessad

Reputation: 1229

sorting the order of my tables in admin - rails

In the admin end when I view the 'users' table, I'd like it to be ordered by :id

I can do this manually each time I go to that admin screen, but is there a way to default to showing the users table ordered by id?

admin/users_controller.rb:

class Admin::UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin

  layout 'admin_application'

  def index
    @search = User.search(params[:q])
    @users = @search.result
  end

And in the admin/users/index.html.haml

%table.users_table
  %thead
    %tr
      %th= sort_link(@search, :id, 'ID')
      %th= sort_link(@search, :name, 'Name')
      %th= sort_link(@search, :username, 'Username')
      %th Email
      %th City
      %th Review count
      %th Last logged in time
      %th
      %th
      %th
  %tbody
    - @users.each do |user|
      %tr
        %td= user.id
        %td= user.name
        %td= user.username
        %td= user.email
        %td= user.city
        %td= user.reviews.count
        - if user.has_logged_in?
          %td= user.last_login.to_s(:long)
        - else
          %td No login yet
        %td= link_to 'Show', admin_user_path(user)
        %td= link_to 'Edit', edit_admin_user_path(user)
        %td= link_to 'Destroy', admin_user_path(user), :method => :delete, :data => { :confirm => 'Are you sure?' }

Upvotes: 1

Views: 75

Answers (2)

Dheer
Dheer

Reputation: 793

In User model add scope like:

default_scope order: 'id asc'

Upvotes: 0

Alok Anand
Alok Anand

Reputation: 3356

Add following line to top of your User ActiveRecord class

default_scope order('id ASC')

You will get AR object collection in order of ascending user id.

Upvotes: 2

Related Questions