ernie/squeel — Issue #86: Duplicate joins created when using has_many :through and explicit joins
Author: dvandersluis
Created: 2011-12-18 16:01:26+00:00
State: open

I had originally thought this was a problem in Rails [rails/rails#4016], but it seems that squeel is at least partially the culprit. Given the small example app at https://github.com/dvandersluis/rails-issue-4016/tree/squeel, the following code produces a duplicate join:

class Client < ActiveRecord::Base
has_many :jobs
has_many :job_applications, :through => :jobs
end

class Job < ActiveRecord::Base
has_many :job_applications
belongs_to :client
end

class JobApplications < ActiveRecord::Base
belongs_to :job
end

irb(main):001:0> Client.find(1).job_applications.joins(:job)
ActiveRecord::StatementInvalid: Mysql2::Error: Not unique table/alias: 'jobs': SELECT `job_applications`.* FROM `job_applications` INNER JOIN `jobs` ON `jobs`.`id` = `job_applications`.`job_id` INNER JOIN `jobs` ON `job_applications`.`job_id` = `jobs`.`id` WHERE `jobs`.`client_id` = 1

Without squeel it produces:

irb(main):001:0> Client.find(1).job_applications.joins(:job).to_sql
=> "SELECT `job_applications`.* FROM `job_applications` INNER JOIN `jobs` `jobs_job_applications` ON `jobs_job_applications`.`id` = `job_applications`.`job_id` INNER JOIN `jobs` ON `job_applications`.`job_id` = `jobs`.`id` WHERE `jobs`.`client_id` = 1"