在rails_admin中,如何过滤关联计数?

时间:2014-10-03 14:32:26

标签: ruby-on-rails ruby rails-admin

使用rails_admin 0.6.2,我为关联对象的数量添加了一个自定义字段。例如,在博客帖子列表中,显示每个帖子有多少条评论。

config.model Post do
  list do
    field :id
    field :comment_count, :integer do
      def value
        bindings[:object].comment.count
      end
      filterable true
    end

我希望能够根据此号码进行过滤 - 向我显示0条评论,1到10之间等等。

现在它无法做到这一点,因为这个计数只是用N + 1查询创建的;每次列出帖子时,都会查询评论计数。我需要它为其先前的帖子查询添加WHERE条件。

2 个答案:

答案 0 :(得分:7)

使用范围

您可以指定列表视图可以使用的范围,它将为每个范围创建一个选项卡。例如:

list do
  scopes [:with_comments, :with_no_comments]
 ...

然后你只需要模型范围检查那些。例如:

# app/models/post.rb
scope :with_comments, -> {
  where("id IN (#{Comment.select("DISTINCT post_id").to_sql})")
}

答案 1 :(得分:0)

您可以在帖子模型has_many :comments, counter_cache: true上执行此操作。然后只需添加过滤器范围。它会更快。结帐ActiveRecord的counter_cache文档。