How can I retrieve the alias that active_record generates? I would like to create a method table_alias_of that takes 3 arguments
- The model where the query is run from
- The includes hash
- 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.