开发者

: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. 开发者_StackOverflow中文版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?


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")


something like

:conditions => { :this_table => { :state => 1 } }


Are you using any of the fields from the :include tables in the query (as :conditions / :order etc) ? If not, and you just need to load records, you can do it with separate query:

records = Bar.all(:joins => ..., :conditions => ..., ...)
Bar.send(:preload_associations, records, [:association1, :association2 ... ])

preload_associations is protected method (see more in this answer), but using :joins and :include together usually produces huge SQL query, which is far away from managable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜