1

How can I retrieve the alias that active_record generates? I would like to create a method table_alias_of that takes 3 arguments

  1. The model where the query is run from
  2. The includes hash
  3. Path of associations

To address associations in the conditions or in the order.

Example: All includes point to same table "contacts".

includes = ["end_user", "reseller", "distributor"]

e = table_alias_of(Maintenance, includes, "end_user") 
e #=> contacts
r = table_alias_of(Maintenance, includes, "reseller") 
r #=> maintenances_contacts
d = table_alias_of(Maintenance, includes, "distributor") 
d #=> maintenances_contacts_2

Maintenance.all(
    :include => includes, 
    :conditions => ["#{d}.name=?", x], 
    :order => "#{r}.name, #{e}.name"

How could I implement table_alias_of? It should be compatible with rails 2.3.x as well as rails 3.1.x

What I already did/thought of is

  • Letting rails generating the from clause string and parsing it with regex. But this breaks when switching to rails 3/arel.
  • Writing the :join or :from yourself because then you specify the table aliases. But this makes the code more complex
  • Parsing :include and generating the join with code. That's just copying ar logic.
Tom Maeckelberghe
  • 1,969
  • 3
  • 21
  • 24
  • What is `table_alias_of`? The only method I know of like that is `table_alias_for` but it only takes one argument. – tadman Dec 07 '11 at 16:14
  • able_alias_for doc: Truncates a table alias according to the limits of the current adapter. I am searching something that will tell me not only how it truncates but also how it calculates the table alias – Tom Maeckelberghe Dec 09 '11 at 10:24

0 Answers0