在管理员端,当我查看'用户'表时,我希望按以下顺序排序:id
我每次进入该管理界面时都可以手动执行此操作,但有没有办法默认显示按ID排序的用户表?
管理员/ 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
在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?' }
答案 0 :(得分:2)
将以下行添加到User ActiveRecord类的顶部
default_scope order('id ASC')
您将按升序用户ID的顺序获得AR对象集合。
答案 1 :(得分:0)
在用户模型中添加范围,如:
default_scope order: 'id asc'