簡體   English   中英

在rails_admin中,如何過濾關聯計數?

[英]In rails_admin, how can I filter on an association count?

使用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條件。

使用范圍

您可以指定列表視圖可以使用的范圍,它將為每個范圍創建一個選項卡。 例如:

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})")
}

你可以在Post模型has_many :comments, counter_cache: true上執行此操作。 然后只需添加過濾器范圍。 它會更快。 檢出ActiveRecord的counter_cache文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM