This project is archived and is in readonly mode.

#2357 new
Steffen Bartsch

Predictable Table Aliases in Joins

Reported by Steffen Bartsch | March 27th, 2009 @ 02:36 PM | in 3.x

Right now, ActiveRecord assigns table aliases for association joins fairly unpredictable. The first association to a certain table keeps the table name. Further joins with associations to that table use aliases consisting of the association names in the path.

With the great flexibility of named_scoped, it is increasingly common for app developers not to know about already existing joins at coding time. Also, the order of joins in a Hash is undefined in Ruby 1.8.

Table aliases are needed, though, for building conditions on the association tables. With our plugin declarative_authorization, which is using named_scopes to rewrite queries according to permissions, we frequently run into problems because of unpredictable table aliases.

I'd like to propose (and am willing to implement) the following simple API for querying the expected table alias for certain association join path, to be used by app developers


# Example:
company_alias = User.table_alias_for(:home_branch, :company)
    :joins      => {:home_branch => :company}, 
    :conditions => ["#{company_alias}.name LIKE ?", search])

The actual algorithm for determining the table alias should work as follows:

  • All joins receive a table alias according to the join path
  • Association names in a path are concatenated into a long alias, i.e. :home_branch, :company => "home_branch_company"
  • Aliases exceeding the max alias name length are shortened to (max_length - 9) and concatenated with an underscore and 8 characters from the long alias string hash in hex


long_alias = join_path * "_"
table_alias = long_alias[0, max_table_alias_length - 9] + 
    "_" + ("%x" % long_alias.hash)[0,8]


Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

Shared Ticket Bins