ActiveAdmin 索引 - 对计数列进行排序或过滤?
ActiveAdmin index - sort or filter on count column?
我需要 sort/filter ActiveAdmin 视图中的一列。该列是子对象的计数。具体来说,该模型如下所示:
class Location < ActiveRecord::Base
...
has_many :things
...
ActiveAdmin 页面需要有一个专栏,我是这样的:
column 'Thing Count', :sortable => 'Thing Count' do |location|
location.things.length
end
然而,排序实际上不起作用,而且我也没有想出一种使过滤起作用的方法。我已经尝试了几种变体:
:filter 'Thing Count'
没有成功。有没有人成功地让 ActiveAdmin 对子对象的计数列进行排序或过滤?如果是这样怎么办?谢谢!
ActiveAdmin 只能对数据库列进行筛选。
您可以执行以下操作:
- 在
belongs_to
侧/事物模型上创建一个 counter_cache 列。
- 为该列创建一个过滤器
filter :things_count
- 重新计算每个事物的计数器。
示例:
def up
add_column :projects, :tasks_count, :integer, :default => 0
Project.reset_column_information
Project.find(:all).each do |p|
Project.update_counters p.id, :tasks_count => p.tasks.length
end
end
def down
remove_column :projects, :tasks_count
end
class Location
has_many :things
def self.all_things
joins(:things).select("locations.id as loc_id, count(things.*) as count").group("locations.id").order("count(things.*)")
end
end
我需要 sort/filter ActiveAdmin 视图中的一列。该列是子对象的计数。具体来说,该模型如下所示:
class Location < ActiveRecord::Base
...
has_many :things
...
ActiveAdmin 页面需要有一个专栏,我是这样的:
column 'Thing Count', :sortable => 'Thing Count' do |location|
location.things.length
end
然而,排序实际上不起作用,而且我也没有想出一种使过滤起作用的方法。我已经尝试了几种变体:
:filter 'Thing Count'
没有成功。有没有人成功地让 ActiveAdmin 对子对象的计数列进行排序或过滤?如果是这样怎么办?谢谢!
ActiveAdmin 只能对数据库列进行筛选。
您可以执行以下操作:
- 在
belongs_to
侧/事物模型上创建一个 counter_cache 列。 - 为该列创建一个过滤器
filter :things_count
- 重新计算每个事物的计数器。
示例:
def up
add_column :projects, :tasks_count, :integer, :default => 0
Project.reset_column_information
Project.find(:all).each do |p|
Project.update_counters p.id, :tasks_count => p.tasks.length
end
end
def down
remove_column :projects, :tasks_count
end
class Location
has_many :things
def self.all_things
joins(:things).select("locations.id as loc_id, count(things.*) as count").group("locations.id").order("count(things.*)")
end
end