Skip to content

Commit

Permalink
Use count(:all) for associations in HasMany field (thoughtbot#721)
Browse files Browse the repository at this point in the history
Problem: Calling `count` on an association can cause invalid SQL queries
to be created where the `SELECT COUNT(a, b, c)` function receives
multiple  columns. This will cause a `StatementInvalid` exception later
on.

Solution: Use `count(:all)`, which generates a `SELECT COUNT(*)...`
query independently of the association.
  • Loading branch information
klaseskilson authored and fwolfst committed Mar 8, 2017
1 parent 1d65b9d commit 4a1a93d
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
2 changes: 1 addition & 1 deletion app/views/fields/has_many/_show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ from the associated resource class's dashboard.
<%= t(
'administrate.fields.has_many.more',
count: field.limit,
total_count: field.data.count,
total_count: field.data.count(:all),
) %>
</span>
<% end %>
Expand Down
2 changes: 1 addition & 1 deletion lib/administrate/field/has_many.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def resources
end

def more_than_limit?
data.count > limit
data.count(:all) > limit
end

private
Expand Down
7 changes: 6 additions & 1 deletion spec/support/mock_relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ def initialize(data)
@data = data
end

delegate :==, :count, to: :@data
delegate :==, to: :@data

def limit(n)
@data.first(n)
end

def count(column = nil)
return @data.count if column == :all
@data.count(column)
end
end

0 comments on commit 4a1a93d

Please sign in to comment.