rails/rails — Issue #4729: STI Polymorphcis is broken in Rails3.1
Author: ciantainc
Created: 2012-01-27 20:50:57+00:00
State: open

I am using single table inheritance (STI) polymorphic feature in my app. I just migrated from rails 3.0.10 to 3.1.3 on windows7.

Here is the use case:
class Collaboration < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
belongs_to :member, :polymorphic => true
end
class Student < User
has_many :collaborations, :as => :owner
has_many :advisors, :through => :collaborations, :source => :member, :source_type => "Advisor"
end
class Advisor < User
has_many :collaborations, :as => :member
has_many :students, :through => :collaborations, :source => :owner, :source_type => "Student"
end

I created an entry in 'collaborations' table. Here is the output of Collaboration.all.inspect
[#]

Here is the issue:
a1 = Advisor.find(68)
a1.collaborations.to_sql produces the following:
=> "SELECT `collaborations`.* FROM `collaborations` WHERE `collaborations`.`member_id` = 68 AND `collaborations`.`member_type` = 'User'"

instead of
=> "SELECT `collaborations`.* FROM `collaborations` WHERE `collaborations`.`member_id` = 68 AND `collaborations`.`member_type` = 'Advisor'"

Is this a bug in Rails 3.1? The right behavior should be to use child class type (Advisor) instead of base class type (User) in the SQL construct. Is there a fix or workaround for this issue? I am stuck with this and a prompt response would be greatly appreciated. Thanks.