1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Use count(:all) in HasManyAssociation#count_records

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.

This also includes a test case that, before the fix, broke.
This commit is contained in:
Klas Eskilson 2017-01-03 16:24:42 -08:00
parent 6599e07674
commit 4a7b4f88cd
4 changed files with 16 additions and 1 deletions

View file

@ -1,3 +1,8 @@
* Use `count(:all)` in `HasManyAssociation#count_records` to prevent invalid
SQL queries for association counting.
*Klas Eskilson*
* Deprecate locking records with unpersisted changes. * Deprecate locking records with unpersisted changes.
*Marc Schütz* *Marc Schütz*

View file

@ -66,7 +66,7 @@ module ActiveRecord
count = if reflection.has_cached_counter? count = if reflection.has_cached_counter?
owner._read_attribute(reflection.counter_cache_column).to_i owner._read_attribute(reflection.counter_cache_column).to_i
else else
scope.count scope.count(:all)
end end
# If there's nothing in the database and @target has no new records # If there's nothing in the database and @target has no new records

View file

@ -2446,6 +2446,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [first_bulb, second_bulb], car.bulbs assert_equal [first_bulb, second_bulb], car.bulbs
end end
test "association size calculation works with default scoped selects when not previously fetched" do
firm = Firm.create!(name: "Firm")
5.times { firm.developers_with_select << Developer.create!(name: "Developer") }
same_firm = Firm.find(firm.id)
assert_equal 5, same_firm.developers_with_select.size
end
test "double insertion of new object to association when same association used in the after create callback of a new object" do test "double insertion of new object to association when same association used in the after create callback of a new object" do
reset_callbacks(:save, Bulb) do reset_callbacks(:save, Bulb) do
Bulb.after_save { |record| record.car.bulbs.load } Bulb.after_save { |record| record.car.bulbs.load }

View file

@ -85,6 +85,8 @@ class Firm < Company
has_many :association_with_references, -> { references(:foo) }, class_name: "Client" has_many :association_with_references, -> { references(:foo) }, class_name: "Client"
has_many :developers_with_select, -> { select("id, name, first_name") }, class_name: "Developer"
has_one :lead_developer, class_name: "Developer" has_one :lead_developer, class_name: "Developer"
has_many :projects has_many :projects