This project is archived and is in readonly mode.
Generated sql for has_many :through relation wrong when used with STI
-
Andrew White
- State changed from new to open
- Assigned user set to Andrew White
- Importance changed from to Low
Yep, I've confirmed this - if you define the association in the base class it works as expected though.
-
eli.b
Hey-
Thanks Andrew!
'if you define the association in the base class it works as expected though.' What do you mean exactly? If I just put the class definition of Third inside second.rb? Sorry, I'm a little new to the not-so-simple associations game.
-e -
Andrew White
Using your models it would be like this:
class First < ActiveRecord::Base has_many :tags has_many :seconds, :through => :tags end class Second < ActiveRecord::Base has_many :tags has_many :firsts, :through => :tags end class Third < Second; end class Tag < ActiveRecord::Base belongs_to :first belongs_to :seconds endSetting it up this way will return the appropriate models when use First.joins(:seconds).where(:seconds => { :id => 1 }). Using more descriptive model names will make it clearer:
class Vehicle < ActiveRecord::Base has_many :taggings has_many :tags, :through => :taggings end class Car < Vehicle; end class Van < Vehicle; end class Motorbike < Vehicle; end class Tag < ActiveRecord::Base has_many :taggings has_many :vehicles, :through => :taggings end class Tagging < ActiveRecord::Base belongs_to :vehicle belongs_to :tag end >> Tag.joins(:vehicles).where("vehicles.id = 1").to_sql => "SELECT tags.* FROM tags INNER JOIN taggings ON tags.id = taggings.tag_id INNER JOIN vehicles ON taggings.vehicle_id = vehicles.id WHERE vehicles.id = 1"