diff options
author | Pratik Naik <pratiknaik@gmail.com> | 2009-07-13 16:25:33 +0100 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2009-07-13 16:29:19 +0100 |
commit | 373b053dc8b99dac1abc3879a17a2bf8c30302b5 (patch) | |
tree | 04e194875edb6b9e5fbdcd2907e5439fba5a0eb8 /activerecord | |
parent | c863388039ff6e97447be86184d41fbf30f0f389 (diff) | |
download | rails-373b053dc8b99dac1abc3879a17a2bf8c30302b5.tar.gz rails-373b053dc8b99dac1abc3879a17a2bf8c30302b5.tar.bz2 rails-373b053dc8b99dac1abc3879a17a2bf8c30302b5.zip |
Optimize <association>_ids for hm:t with belongs_to source
Diffstat (limited to 'activerecord')
-rwxr-xr-x | activerecord/lib/active_record/associations.rb | 9 | ||||
-rw-r--r-- | activerecord/test/cases/associations/has_many_through_associations_test.rb | 8 |
2 files changed, 14 insertions, 3 deletions
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 10ecd068d3..1b884fd2ab 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1273,9 +1273,16 @@ module ActiveRecord if send(reflection.name).loaded? || reflection.options[:finder_sql] send(reflection.name).map(&:id) else - send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id) + if reflection.through_reflection && reflection.source_reflection.belongs_to? + through = reflection.through_reflection + primary_key = reflection.source_reflection.primary_key_name + send(through.name).all(:select => "DISTINCT #{through.quoted_table_name}.#{primary_key}").map(&:"#{primary_key}") + else + send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id) + end end end + end def collection_accessor_methods(reflection, association_proxy_class, writer = true) diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 7a4712d7c8..8529ff0285 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -243,8 +243,12 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal 2, people(:michael).jobs.size end - def test_get_ids - assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort + def test_get_ids_for_belongs_to_source + assert_sql(/DISTINCT/) { assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort } + end + + def test_get_ids_for_has_many_source + assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids end def test_get_ids_for_loaded_associations |