Rails 2.3.9 weirdness in eager loading an ordered has_many :through assocation
Snappy title, eh.
I ran into this bug while trying to update an app to 2.3.9. I know of a workaround but I’m struggling to write a test that reproduces it in the AR source. So until I get around to doing that, heres the weirdness:
class Job < ActiveRecord::Base has_many :job_memberships, :dependent => :destroy has_many :users, :through => :job_memberships, :order => "users.last_name, users.first_name" end
(I’m sure you can guess what job_memberships and users look like)
Job.find(165, :include => :users)
Results in:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'users.last_name' in 'order clause': SELECT `job_memberships`.* FROM `job_memberships` WHERE (`job_memberships`.job_id = 165) ORDER BY users.last_name, users.first_name
Now a similar bug exists and has been fixed, which lead me to the workaround.
In job.rb, add the :source key to the has_many through definition
has_many :users, :through => :job_memberships, :order => "users.last_name, users.first_name", :source => :user
… and the eager loading works.
I’ve been so busy trying to write a test that replicates it in the AR test suite that I’ve not actually looked into fixing it, but I suspect like the bug mentioned above it’s in the preload_through_records method in association_preload.rb.
I’ll try again later to write it, but in the mean time this may be useful to someone :)