diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 54215cf88d7550d687e1d5428dc075bb756689b8..862ff201debb18f7bb80294445a20a6ab1443931 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -174,8 +174,6 @@ 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] @@ -366,6 +364,16 @@ def add_to_target(record) record end + def scope(opts = {}) + scope = super() + scope.none! if opts.fetch(:nullify, true) && null_scope? + scope + end + + def null_scope? + owner.new_record? && !foreign_key_present? + end + private def custom_counter_sql diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 536e108f0ed7874dcff67fb692b66e3f1663b46b..50f9fca7c086a053ec033a3672dfac3c99247952 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -31,7 +31,7 @@ class CollectionProxy < Relation def initialize(association) #:nodoc: @association = association super association.klass, association.klass.arel_table - merge! association.scope + merge! association.scope(nullify: false) end def target @@ -835,9 +835,8 @@ def scoping # Returns a Relation object for the records in this association def scope association = @association - scope = @association.scope - scope.none! if @association.owner.new_record? - scope.extending! do + + @association.scope.extending! do define_method(:proxy_association) { association } end end diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb index 4c1c91e3dff156f21c89eea74a4327d3dcc76043..f8f7a6c9769618179a2b5b31f5828abccc1139ae 100644 --- a/activerecord/lib/active_record/null_relation.rb +++ b/activerecord/lib/active_record/null_relation.rb @@ -46,7 +46,7 @@ def where_values_hash {} end - def count + def count(*) 0 end