:include and table aliasing
        Posted  
        
            by dondo
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by dondo
        
        
        
        Published on 2010-06-02T21:42:33Z
        Indexed on 
            2010/06/02
            21:44 UTC
        
        
        Read the original article
        Hit count: 239
        
ruby-on-rails
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?
© Stack Overflow or respective owner