In rails_admin, how can I filter on an association count?
Asked Answered
R

2

2

Using rails_admin 0.6.2, I've added a custom field for a count of associated objects. For example, in a list of blog posts, show how many comments each has.

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

I want to be able to filter based on this number - show me posts with 0 comments, between 1 and 10, etc.

Right now there's no way it could do that, as this count is just created with an N+1 query; every time it lists a post, it queries for the comment count. I would need it to add a WHERE condition to its earlier query for the posts.

Rita answered 3/10, 2014 at 14:32 Comment(0)
R
7

Use a scope

You can specify scopes that the list view can use and it will create a tab for each scope. Eg:

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

Then you just need model scopes that check for those. Eg:

# app/models/post.rb
scope :with_comments, -> {
  where("id IN (#{Comment.select("DISTINCT post_id").to_sql})")
}
Rita answered 3/10, 2014 at 14:52 Comment(0)
N
0

You can do this on Post model has_many :comments, counter_cache: true. Then just add scope of filter. It will be faster. Checkout counter_cache docs for ActiveRecord.

Nutritionist answered 25/1, 2016 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.