Class: ActiveRecord::Associations::AliasTracker

Inherits:
Object
  • Object
show all
Defined in:
activerecord/lib/active_record/associations/alias_tracker.rb

Overview

Keeps track of table aliases for ActiveRecord::Associations::ClassMethods::JoinDependency and ActiveRecord::Associations::ThroughAssociationScope

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection = Base.connection, table_joins = []) ⇒ AliasTracker

table_joins is an array of arel joins which might conflict with the aliases we assign here



11
12
13
14
15
# File 'activerecord/lib/active_record/associations/alias_tracker.rb', line 11

def initialize(connection = Base.connection, table_joins = [])
  @aliases     = Hash.new { |h,k| h[k] = initial_count_for(k) }
  @table_joins = table_joins
  @connection  = connection
end

Instance Attribute Details

#aliasesObject (readonly)

Returns the value of attribute aliases



8
9
10
# File 'activerecord/lib/active_record/associations/alias_tracker.rb', line 8

def aliases
  @aliases
end

#connectionObject (readonly)

Returns the value of attribute connection



8
9
10
# File 'activerecord/lib/active_record/associations/alias_tracker.rb', line 8

def connection
  @connection
end

#table_joinsObject (readonly)

Returns the value of attribute table_joins



8
9
10
# File 'activerecord/lib/active_record/associations/alias_tracker.rb', line 8

def table_joins
  @table_joins
end

Instance Method Details

#aliased_name_for(table_name, aliased_name = nil) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'activerecord/lib/active_record/associations/alias_tracker.rb', line 27

def aliased_name_for(table_name, aliased_name = nil)
  aliased_name ||= table_name

  if aliases[table_name].zero?
    # If it's zero, we can have our table_name
    aliases[table_name] = 1
    table_name
  else
    # Otherwise, we need to use an alias
    aliased_name = connection.table_alias_for(aliased_name)

    # Update the count
    aliases[aliased_name] += 1

    if aliases[aliased_name] > 1
      "#{truncate(aliased_name)}_#{aliases[aliased_name]}"
    else
      aliased_name
    end
  end
end

#aliased_table_for(table_name, aliased_name = nil) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'activerecord/lib/active_record/associations/alias_tracker.rb', line 17

def aliased_table_for(table_name, aliased_name = nil)
  table_alias = aliased_name_for(table_name, aliased_name)

  if table_alias == table_name
    Arel::Table.new(table_name)
  else
    Arel::Table.new(table_name).alias(table_alias)
  end
end