Permalink
Browse files

Relations built off collection associations with an unsaved owner sho…

…uld 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.
  • Loading branch information...
jonleighton committed Nov 9, 2012
1 parent c33cfa6 commit 0130c17476b754aea20faf6914686c5d4c7086b9
@@ -835,8 +835,9 @@ def scoping
# 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
@@ -1648,4 +1648,13 @@ def test_collection_association_with_private_kernel_method
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

2 comments on commit 0130c17

@henrik

This comment has been minimized.

Show comment Hide comment
@henrik

henrik Nov 9, 2012

Contributor

Lovely!

Contributor

henrik replied Nov 9, 2012

Lovely!

@vipulnsward

This comment has been minimized.

Show comment Hide comment
@vipulnsward

vipulnsward Nov 9, 2012

Member

Awesome. Thanks!

Member

vipulnsward replied Nov 9, 2012

Awesome. Thanks!

Please sign in to comment.