Hi everybody,

I would have expect rails to automatically alias the tables when generating 
an SQL request with STI models.

The problem is that using scope with the current behavior is not handy.

Let say I have a generic table 'lookups' and its model 'Lookup'.

>From it inherited many other models for example 'Location' and 'Language'.

User.includes(:locations, :languages).where(locations: { id: 3}, languages: 
{id: 4} )

will generate something like :

SELECT ...
FROM users
LEFT OUTER JOIN `lookups` ON `lookups`.`associated_id` = `users`.`id`
AND `lookups`.`type` IN ('Location')
LEFT OUTER JOIN `lookups` `languages_users` ON 
`languages_users`.`associated_id` = `users`.`id`
AND `languages_users`.`type` IN ('Language')
WHERE `locations`.`id` = 3 AND `languages`.`id` = 5;

raising an sql error : "Unknown column 'locations.id' in 'where clause': 
..."


So, in that case I could easily adapt my line of code doing : 

User.includes(:locations, :languages).where('lookups.id = 3 AND 
languages_users.id = 5')

But more than being less clear and readable. When playing with scope it 
gets more and more unexpected : 

In User model, I have two scopes : 
scope :with_location, ->(location) { includes(:locations).where('lookups.id 
= ?', location) }
scope :with_language, ->(language) { 
includes(:languages).where('languages_users.id = ? ', language) }

Now I would get the problem that calling
User.with_language(5) 
would not work because generating 

SELECT ...
FROM users
LEFT OUTER JOIN `lookups` ON `lookups`.`associated_id` = `users`.`id`
AND `lookups`.`type` IN ('Language')
WHERE `lookups`.`id` = 3


It seems to me that automatically aliasing the table with the name of the 
STI model would make more sense : 

SELECT ...
FROM users
LEFT OUTER JOIN `lookups` `languages` ON `languages`.`associated_id` = 
`users`.`id`
AND `languages`.`type` IN ('Language')
WHERE `languages`.`id` = 3


What do you think about that ? Is there something I miss ?



-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to