Rails - ActiveAdmin 创建关系计数列可排序 [英] Rails - ActiveAdmin create relationship count column sortable

查看:18
本文介绍了Rails - ActiveAdmin 创建关系计数列可排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ActiveAdmin,我正在尝试显示列名 Active Jobs 和计数

I am working on ActiveAdmin and I am trying to display a column name Active Jobs with a count

获取这个计数涉及三个模型

There are three models involved in getting this count

 1. Staffroom 
 2. StaffroomPage
 3. Job



class StaffroomPage < ActiveRecord::Base
  belongs_to :staffroom

class Staffroom < ActiveRecord::Base
  has_one :staffroom_page
  has_many :jobs

class Job < ActiveRecord::Base
  belongs_to :staffroom

现在在 admin/staffroom_pages.rb 中我可以显示列和计数

Now inside the admin/staffroom_pages.rb I am able to display the column and the count

column :active_jobs, sortable: 'active_jobs' do |staffroom_page|
  staffroom_page.staffroom.jobs.where(:state=> 'active').count
end

但是我无法通过 active_jobs 对数据进行排序,并且看到以下错误

However I am not able to sort the data via active_jobs and I see the following error

PG::UndefinedColumn:错误:active_jobs"列不存在

PG::UndefinedColumn: ERROR: column "active_jobs" does not exist

所以问题是如何使 active_jobs 列的排序工作,请注意,这不是页面上唯一的可排序列,几乎所有列都可排序,这是唯一一个不可排序的列工作.

So the question is how to make the sort to work for column active_jobs, please note that this is not the only sortable column on page, almost all columns are sortable and this is the only one not working.

推荐答案

来自 这篇文章 在 activeadmin github 上,此问题的可能解决方法是

From this post on the activeadmin github a possible workaround to this problem would be

index do
  column :active_jobs, sortable: 'active_jobs' do |staffroom_page|
    staffroom_page.staffroom.jobs.where(:state=> 'active').count
  end
end

controller do


def scoped_collection
  super.joins(
    %(LEFT JOIN "jobs" ON "staffroom_pages"."staffroom_id" = "jobs"."staffroom_id"
        AND "jobs"."state" = 'active'))
      .select('staffroom_pages.*, COUNT(jobs.id) as active_jobs')
      .group('staffroom_pages.id')
  end
end

这篇关于Rails - ActiveAdmin 创建关系计数列可排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆