ActiveAdmin:按关联计数排序

时间:2013-04-10 11:22:42

标签: ruby-on-rails activeadmin

我有以下型号

class User < ActiveRecord::Base
   has_many :reviews
end

class Review < ActiveRecord::Base
   belongs_to :user
end

我想按照每个用户的评论数量对ActiveDdmin页面上的用户进行排序 具有

我试过这个,但没有运气:(来自this SO question

ActiveAdmin.register User do
  filter :name
  index do
    column :name
    column :email
    column "Facebook" do |u|
      if u.provider == "facebook"
        "Yes"
      end
    end
    column "No. of reviews", :sortable => :"reviews.count" do |u|
      u.reviews.count
    end

  end

  controller do
    def scoped_collection
      end_of_association_chain.includes(:reviews)
    end
  end
end

1 个答案:

答案 0 :(得分:6)

我建议您在用户模型上使用counter_cache进行评论,然后直接在ActiveAdmin中使用此列:

index do
  # ...
  column "No. of reviews", :sortable => :reviews_count
end