This project is archived and is in readonly mode.

#6668 new
Greg Hazel

ActiveRecord scopes accumulate joins in reverse order

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

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.

No comments found

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages