Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:include and table aliasing

I'm suffering from a variant of the problem described here:

ActiveRecord assigns table aliases for association joins fairly unpredictably. The first association to a given table keeps the table name. Further joins with associations to that table use aliases including the association names in the path... but it is common for app developers not to know about [other] joins at coding time.

In my case I'm being bitten by a toxic mix of has_many and :include. Many tables in my schema have a state column, and the has_many wants to specify conditions on that column: has_many :foo, :conditions => {:state => 1}. However, since the state column appears in many tables, I disambiguate by explicitly specifying the table name: has_many :foo, :conditions => "this_table.state = 1".

This has worked fine until now, when for efficiency I want to add an :include to preload a fairly deep tree of data. This causes the table to be aliased inconsistently in different code paths. My reading of the tickets referenced above is that this problem is not and will not be fixed in Rails 2.x. However, I don't see any way to apply the suggested workaround (to specify the aliased table name explicitly in the query). I'm happy to specify the table alias explicitly in the has_many statement, but I don't see any way to do so. As such, the workaround doesn't appear applicable to this situation (nor, I presume, in many 'named_scope' scenarios).

Is there a viable workaround?

like image 247
dondo Avatar asked Jun 02 '10 21:06

dondo


1 Answers

Rather than using :include, with the :joins key you can explicitly write the join and give it your own table alias. You do have to hand-specify the join, but it will make your requirements completely unambiguous. eg:

Bar.all(:joins => "INNER JOIN foos AS my_foos ON my_foos.bar_id = bars.id", :conditions =>  "my_foos.state = 1")
like image 73
Taryn East Avatar answered Oct 06 '22 00:10

Taryn East