diff options
author | Jon Leighton <j@jonathanleighton.com> | 2011-01-24 22:25:32 +0000 |
---|---|---|
committer | Jon Leighton <j@jonathanleighton.com> | 2011-01-30 11:58:08 +0000 |
commit | b7bcc7e1905062f330e0a84b93a1ecacfea2a4c0 (patch) | |
tree | 5da246ed31edb652119ce028e1ec29939d664748 | |
parent | e8d7152a89f16a487a3d67d16a63bf065183b405 (diff) | |
download | rails-b7bcc7e1905062f330e0a84b93a1ecacfea2a4c0.tar.gz rails-b7bcc7e1905062f330e0a84b93a1ecacfea2a4c0.tar.bz2 rails-b7bcc7e1905062f330e0a84b93a1ecacfea2a4c0.zip |
DRY up first/last and hence make last benefit from the bugfix in first
-rw-r--r-- | activerecord/lib/active_record/associations/association_collection.rb | 28 | ||||
-rw-r--r-- | activerecord/test/cases/associations/has_many_associations_test.rb | 6 |
2 files changed, 19 insertions, 15 deletions
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 5b9f2f99db..a59de18313 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -36,25 +36,12 @@ module ActiveRecord end end - # Fetches the first one using SQL if possible. def first(*args) - if fetch_first_or_last_using_find?(args) - scoped.first(*args) - else - load_target unless loaded? - args.shift if args.first.kind_of?(Hash) && args.first.empty? - @target.first(*args) - end + first_or_last(:first, *args) end - # Fetches the last one using SQL if possible. def last(*args) - if fetch_first_or_last_using_find?(args) - scoped.last(*args) - else - load_target unless loaded? - @target.last(*args) - end + first_or_last(:last, *args) end def to_ary @@ -560,6 +547,17 @@ module ActiveRecord load_target.select { |r| ids.include?(r.id) } end end + + # Fetches the first/last using SQL if possible, otherwise from the target array. + def first_or_last(type, *args) + if fetch_first_or_last_using_find?(args) + scoped.send(type, *args) + else + load_target unless loaded? + args.shift if args.first.kind_of?(Hash) && args.first.empty? + @target.send(type, *args) + end + end end 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 2ca412d424..3bec9c97f4 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -86,10 +86,16 @@ class HasManyAssociationsTest < ActiveRecord::TestCase Car.create(:name => 'honda') bulbs = Car.first.bulbs bulbs.inspect # to load all instances of bulbs + assert_no_queries do bulbs.first() bulbs.first({}) end + + assert_no_queries do + bulbs.last() + bulbs.last({}) + end end def test_create_resets_cached_counters |