Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #2 from rails/3-2-stable

Merge pull request #6978 from frodsan/count_nosql_unsaved_parent
  • Loading branch information...
commit 851098dfa44f35e1f31d054b4af2f597c87da3b1 2 parents 08b3fb9 + 9896729
bluetrans-deploy bluetrans-deploy authored
17 activerecord/CHANGELOG.md
View
@@ -1,5 +1,22 @@
## Rails 3.2.9 (unreleased)
+* `CollectionAssociation#count` returns 0 without querying if the
+ parent record is new.
+
+ Before:
+
+ person.pets
+ # SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" IS NULL
+ # => 0
+
+ After:
+
+ person.pets
+ # fires without sql query
+ # => 0
+
+ *Francesco Rodriguez*
+
* Fix `reset_counters` crashing on `has_many :through` associations.
Fix #7822.
2  activerecord/lib/active_record/associations/collection_association.rb
View
@@ -190,6 +190,8 @@ def sum(*args)
# association, it will be used for the query. Otherwise, construct options and pass them with
# scope to the target class's +count+.
def count(column_name = nil, count_options = {})
+ return 0 if owner.new_record?
+
column_name, count_options = nil, column_name if column_name.is_a?(Hash)
if options[:counter_sql] || options[:finder_sql]
6 activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
View
@@ -812,6 +812,12 @@ def test_count_with_counter_sql
assert_equal 1, developer.projects.count
end
+ def test_counting_should_not_fire_sql_if_parent_is_unsaved
+ assert_no_queries do
+ assert_equal 0, Developer.new.projects.count
+ end
+ end
+
unless current_adapter?(:PostgreSQLAdapter)
def test_count_with_finder_sql
assert_equal 3, projects(:active_record).developers_with_finder_sql.count
6 activerecord/test/cases/associations/has_many_associations_test.rb
View
@@ -301,6 +301,12 @@ def test_counting_with_association_limit
assert_equal firm.limited_clients.length, firm.limited_clients.count
end
+ def test_counting_should_not_fire_sql_if_parent_is_unsaved
+ assert_no_queries do
+ assert_equal 0, Person.new.readers.count
+ end
+ end
+
def test_finding
assert_equal 2, Firm.find(:first, :order => "id").clients.length
end
6 activerecord/test/cases/associations/has_many_through_associations_test.rb
View
@@ -782,6 +782,12 @@ def test_count_has_many_through_with_named_scope
assert_equal 1, authors(:mary).categories.general.count
end
+ def test_counting_should_not_fire_sql_if_parent_is_unsaved
+ assert_no_queries do
+ assert_equal 0, Person.new.posts.count
+ end
+ end
+
def test_has_many_through_belongs_to_should_update_when_the_through_foreign_key_changes
post = posts(:eager_other)
Please sign in to comment.
Something went wrong with that request. Please try again.