ActiveRecord (2.3.11) accumulates joins in reverse order,
leading to incorrect queries:
>> User.scoped(:joins => "INNER JOIN profiles ON users.id = profiles.user_id").scoped(:joins => "INNER JOIN images ON profiles.image_id = images.id").all
User Load (0.0ms) Mysql2::Error: Unknown column 'profiles.image_id' in 'on clause': SELECT `users`.* FROM `users` INNER JOIN images ON profiles.image_id = images.id INNER JOIN profiles ON users.id = profiles.user_id
However if I reverse the scopes, the query is correctly
formed:
>> User.scoped(:joins => "INNER JOIN images ON profiles.image_id = images.id").scoped(:joins => "INNER JOIN profiles ON users.id = profiles.user_id").all
User Load (1.0ms) SELECT `users`.* FROM `users` INNER JOIN profiles ON users.id = profiles.user_id INNER JOIN images ON profiles.image_id = images.id
This appears to be due to ActiveRecord::Base#with_scope, where
the parameters to merge_joins seem to be reversed compared to
:include
elsif key == :include && merge
hash[method][key] = merge_includes(hash[method][key], params[key]).uniq
elsif key == :joins && merge
hash[method][key] = merge_joins(params[key], hash[method][key])
This bug does not seem to apply to Rails 3.0.5.