Skip to content

Commit

Permalink
Merge pull request rails#27561 from fishbrain/count-all-in-has-many-a…
Browse files Browse the repository at this point in the history
…ssociation

Use `count(:all)` in HasManyAssociation#count_records
  • Loading branch information
kamipo committed Jan 3, 2018
1 parent 6346683 commit eef3c89
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
5 changes: 5 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
* Use `count(:all)` in `HasManyAssociation#count_records` to prevent invalid
SQL queries for association counting.

*Klas Eskilson*

* Fix to invoke callbacks when using `update_attribute`.

*Mike Busch*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def count_records
count = if reflection.has_cached_counter?
owner._read_attribute(reflection.counter_cache_column).to_i
else
scope.count
scope.count(:all)
end

# If there's nothing in the database and @target has no new records
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2502,6 +2502,14 @@ def self.name
assert_equal [first_bulb, second_bulb], car.bulbs
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 "prevent double insertion of new object when the parent association loaded in the after save callback" do
reset_callbacks(:save, Bulb) do
Bulb.after_save { |record| record.car.bulbs.load }
Expand Down
2 changes: 2 additions & 0 deletions activerecord/test/models/company.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ class Firm < Company

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_many :projects

Expand Down

0 comments on commit eef3c89

Please sign in to comment.