Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveRecord scopes accumulate joins in reverse order

#6668

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.

Reported by Greg Hazel · April 4th, 2011 @ 04:11 AM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

No comments yet.