如何在 activeadmin 中对索引的自定义列添加排序?

How to add sorting to a custom column on index in activeadmin?

我有这些联想:

class Event < ApplicationRecord
  has_many :users_events
  has_many :users, through: :users_events
end

class UsersEvent < ApplicationRecord
  belongs_to :user
  belongs_to :event
end

class User < ApplicationRecord
  has_many :users_events
  has_many :events, through: :users_events
end

在 activeadmin 中,我将索引页显示为:

index do
  # some columns
  column :total_participants do |event|
    event.users.count
  end
  # other columns
end

这样做,该列中没有排序。如果我这样做:column(:user_count, sortable: 'users') { |event| event.users.count },出现排序,但查询似乎是错误的:Mysql2::Error: Unknown column 'users' in 'order clause': SELECT 'events'.* FROM 'events' ORDER BY 'users' desc LIMIT 30 OFFSET 0

那么,向自定义列添加排序的最佳方式是什么?我做错了什么?谢谢

由于您需要多次使用此列,所以最好cache。 为此,最好向 events 添加一个名为 users_count 的新列,默认值为 0 并在每次有新用户时递增它:

迁移:

add_column :events, :users_count, default: 0
add_index :events, :users_count

型号:

class UsersEvent < ApplicationRecord
  belongs_to :user
  belongs_to :event
  after_create -> {Event.increment_counter(:users_count, self.event.id)}
end

我也不确定为什么你的模型叫做 UsersEvent 而不是 EventUser