ActiveRecord scopes accumulate joins in reverse order #995

Closed
lighthouse-import opened this Issue May 16, 2011 · 0 comments

1 participant

@lighthouse-import

Imported from Lighthouse. Original ticket at: http://rails.lighthouseapp.com/projects/8994/tickets/6668
Created by Greg Hazel - 2011-04-04 03:11:13 UTC

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment