Permalink
Browse files

Merge pull request #12137 from lann/fix_association_first_last

Make CollectionAssociation first/last with integer fetch with query

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information...
rafaelfranca committed Sep 12, 2013
2 parents e1154a6 + 8875e28 commit 33ae757376f6d97f5580bfa6f03ce8da09d7780a
@@ -1,3 +1,8 @@
+* `CollectionAssociation#first`/`#last` (e.g. `has_many`) use a `LIMIT`ed
+ query to fetch results rather than loading the entire collection.
+
+ *Lann Martin*
+
* Make possible to run SQLite rake tasks without the `Rails` constant defined.
*Damien Mathieu*
@@ -528,15 +528,13 @@ def callbacks_for(callback_name)
# * target already loaded
# * owner is new record
# * target contains new or changed record(s)
- # * the first arg is an integer (which indicates the number of records to be returned)
def fetch_first_or_last_using_find?(args)
if args.first.is_a?(Hash)
true
else
!(loaded? ||
owner.new_record? ||
- target.any? { |record| record.new_record? || record.changed? } ||
- args.first.kind_of?(Integer))
+ target.any? { |record| record.new_record? || record.changed? })
end
end
@@ -1414,15 +1414,17 @@ def test_blank_custom_primary_key_on_new_record_should_not_run_queries
end
end
- def test_calling_first_or_last_with_integer_on_association_should_load_association
+ def test_calling_first_or_last_with_integer_on_association_should_not_load_association
firm = companies(:first_firm)
+ firm.clients.create(:name => 'Foo')
+ assert !firm.clients.loaded?
- assert_queries 1 do
+ assert_queries 2 do
firm.clients.first(2)
firm.clients.last(2)
end
- assert firm.clients.loaded?
+ assert !firm.clients.loaded?
end
def test_calling_many_should_count_instead_of_loading_association

0 comments on commit 33ae757

Please sign in to comment.