diff options
author | Jon Leighton <j@jonathanleighton.com> | 2012-11-09 10:35:39 +0000 |
---|---|---|
committer | Jon Leighton <j@jonathanleighton.com> | 2012-11-09 10:38:58 +0000 |
commit | 0130c17476b754aea20faf6914686c5d4c7086b9 (patch) | |
tree | 110c00f74453bee05b38ce3ae435cec0f814eda8 /activerecord | |
parent | c33cfa6379e98a134672ae46580fcb54ce071f4f (diff) | |
download | rails-0130c17476b754aea20faf6914686c5d4c7086b9.tar.gz rails-0130c17476b754aea20faf6914686c5d4c7086b9.tar.bz2 rails-0130c17476b754aea20faf6914686c5d4c7086b9.zip |
Relations built off collection associations with an unsaved owner should be null relations
For example, the following should not run any query on the database:
Post.new.comments.where(body: 'omg').to_a # => []
Fixes #5215.
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/associations/collection_proxy.rb | 5 | ||||
-rw-r--r-- | activerecord/test/cases/associations/has_many_associations_test.rb | 9 |
2 files changed, 12 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index e73f940334..536e108f0e 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -835,8 +835,9 @@ module ActiveRecord # Returns a <tt>Relation</tt> object for the records in this association def scope association = @association - - @association.scope.extending! do + scope = @association.scope + scope.none! if @association.owner.new_record? + scope.extending! do define_method(:proxy_association) { association } end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 50c23c863f..6355094a79 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1648,4 +1648,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase klass = Class.new(ActiveRecord::Base) assert_deprecated { klass.has_many :foo, :counter_sql => 'lol' } end + + test "has many associations on new records use null relations" do + post = Post.new + + assert_no_queries do + assert_equal [], post.comments + assert_equal [], post.comments.where(body: 'omg') + end + end end |