Skip to content

Commit 7e8dfcf

Browse files
authored
Replace data.count with data.size in HasMany field (#2837)
This updates the `HasMany` field to avoid unnecessary `COUNT(*)` database queries by changing the `more_than_limit?` method to use `data.size` instead of `data.count(:all)`. With eager-loaded associations: Administrate preloads child records via `resources.includes(*includes)` when you configure `collection_includes` on your dashboard. On an eager-loaded `ActiveRecord::Relation`, calling `data.size` returns the in-memory `Array#size`, so **no additional SQL** is issued. Without eager-loading: If you haven’t configured any `includes`, then `data` remains an unloaded relation. In that case, `data.size` will fall back to issuing a `SELECT COUNT(*)`, ensuring the behavior stays correct but without the benefit of preloading. In contrast, the original `data.count(:all)` always triggers a `SELECT COUNT(*)` SQL query, even when the records are already loaded, resulting in unnecessary database round-trips.
1 parent 6a82815 commit 7e8dfcf

File tree

2 files changed

+3
-4
lines changed

2 files changed

+3
-4
lines changed

lib/administrate/field/has_many.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def resources(page = 1, order = self.order)
7272
end
7373

7474
def more_than_limit?
75-
paginate? && data.count(:all) > limit
75+
paginate? && data.size > limit
7676
end
7777

7878
def data

spec/support/mock_relation.rb

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@ def limit(n)
1717
@data.first(n)
1818
end
1919

20-
def count(column = nil)
21-
return @data.count if column == :all
22-
@data.count(column)
20+
def size
21+
@data.size
2322
end
2423
end

0 commit comments

Comments
 (0)