Skip to content
This repository
Browse code

Fix hm:t to self table aliasing in construct_scope

  • Loading branch information...
commit 5d37ff6bb2b1f948034bf06e450f2fdb8195c4e5 1 parent 7bffa9d
Ernie Miller authored May 03, 2010 vijaydev committed December 16, 2010
12  activerecord/lib/active_record/associations/through_association_scope.rb
@@ -21,9 +21,17 @@ def construct_create_scope
21 21
         construct_owner_attributes(@reflection)
22 22
       end
23 23
 
  24
+      def aliased_through_table
  25
+        name = @reflection.through_reflection.table_name
  26
+
  27
+        @reflection.table_name == name ?
  28
+          @reflection.through_reflection.klass.arel_table.alias(name + "_join") :
  29
+          @reflection.through_reflection.klass.arel_table
  30
+      end
  31
+
24 32
       # Build SQL conditions from attributes, qualified by table name.
25 33
       def construct_conditions
26  
-        table = @reflection.through_reflection.klass.arel_table
  34
+        table = aliased_through_table
27 35
         conditions = construct_quoted_owner_attributes(@reflection.through_reflection).map do |attr, value|
28 36
           table[attr].eq(value)
29 37
         end
@@ -53,7 +61,7 @@ def construct_select(custom_select = nil)
53 61
       end
54 62
 
55 63
       def construct_joins
56  
-        right = @reflection.through_reflection.klass.arel_table
  64
+        right = aliased_through_table
57 65
         left  = @reflection.klass.arel_table
58 66
 
59 67
         conditions = []
2  activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -392,7 +392,7 @@ def test_has_many_association_through_a_has_many_association_to_self
392 392
     sarah = Person.create!(:first_name => 'Sarah', :primary_contact_id => people(:susan).id, :gender => 'F', :number1_fan_id => 1)
393 393
     john = Person.create!(:first_name => 'John', :primary_contact_id => sarah.id, :gender => 'M', :number1_fan_id => 1)
394 394
     assert_equal sarah.agents, [john]
395  
-    assert_equal people(:susan).agents_of_agents, [john]
  395
+    assert_equal people(:susan).agents.map(&:agents).flatten, people(:susan).agents_of_agents
396 396
   end
397 397
 
398 398
   def test_collection_singular_ids_getter_with_string_primary_keys
1  activerecord/test/models/person.rb
@@ -12,6 +12,7 @@ class Person < ActiveRecord::Base
12 12
 
13 13
   belongs_to :primary_contact, :class_name => 'Person'
14 14
   has_many :agents, :class_name => 'Person', :foreign_key => 'primary_contact_id'
  15
+  has_many :agents_of_agents, :through => :agents, :source => :agents
15 16
   belongs_to :number1_fan, :class_name => 'Person'
16 17
 
17 18
   scope :males, :conditions => { :gender => 'M' }

0 notes on commit 5d37ff6

Please sign in to comment.
Something went wrong with that request. Please try again.