In rails_admin, how can I filter on the association account?

Using rails_admin 0.6.2, I added a custom field for counting related objects. For example, in the list of blog posts, show how many comments everyone 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 is no way to do this, since this account has just been created with the request N + 1; every time he posts a post, he requests a comment counter. I would need to add a WHERE to his earlier request for messages.

+1
source share
2 answers

Use area

You can specify areas that the list view can use and create a tab for each area. For instance:

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

Then you need only those models that test them. For instance:

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

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

0
source

Source: https://habr.com/ru/post/903386/


All Articles