This project is archived and is in readonly mode.
Constructed SQL is wrong for multiple :joins based on has_many with :conditions
Reported by Georg Ledermann | July 14th, 2009 @ 10:11 AM | in 2.x
The generated INNER JOIN statement is wrong if there are multiple has_many with :conditions and all are joined. See this example:
class Agreement < ActiveRecord::Base
has_many :vendor_involvements, :class_name => 'Involvement', :as => :object, :conditions => { :role => 'vendor' }
has_many :contractor_involvements, :class_name => 'Involvement', :as => :object, :conditions => { :role => 'contractor' }
end
class Involvement < ActiveRecord::Base
belongs_to :object, :polymorphic => true
end
Agreement.find :all, :joins => [ :vendor_involvements, :contractor_involvements ]
This SQL query is generated:
SELECT `agreements`.*
FROM `agreements`
INNER JOIN `involvements`
ON `involvements`.object_id = `agreements`.id
AND `involvements`.object_type = 'Agreement'
AND `involvements`.`role` = 'vendor'
INNER JOIN `involvements` contractor_involvements_agreements
ON `contractor_involvements_agreements`.object_id = `agreements`.id
AND `contractor_involvements_agreements`.object_type = 'Agreement'
AND `involvements`.`role` = 'contractor'
This is wrong, because in the last line it should be
instead of... AND
contractor_involvements_agreements.role
= 'contractor'
... AND
involvements.role
= 'contractor'
There should be used the alias, not the table name.
Comments and changes to this ticket
-
Georg Ledermann July 20th, 2009 @ 09:15 PM
- Tag changed from 2.3.2, conditions, has_many, join, joins, sql to 2.3.2, 2.3.3, activerecord, conditions, has_many, join, joins, sql
Still occurs in Rails 2.3.3
-
Georg Ledermann July 23rd, 2009 @ 05:41 PM
- Tag changed from 2.3.2, 2.3.3, activerecord, conditions, has_many, join, joins, sql to 2.3.2, activerecord, conditions, has_many, join, joins, sql
Please ignore my last comment - it's not true. The bug IS fixed in Rails 2.3.3. Thanks!
http://github.com/rails/rails/commit/489abfd3b23f3c4b3de86aeb3bde39...
-
Michael Koziarski August 3rd, 2009 @ 06:06 AM
- State changed from new to resolved
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
Referenced by
- 4472 :joins and :include behave differently with :conditions This issue is very similar to Issue 2908