STI と Polymorphic を同時に使うとハマる
以下の様なクラスがあるとき
class Company < AR::Base has_many :employments has_many :engineers, through: :employments, source: :employee, source_type: 'Engineer' end # STI の基底クラス class Employee < AR::Base; end # STI class Engineer < Employee; end # Polymorphic class Employment < AR::Base belongs_to :company belongs_to :employee, polymorphic: true end
この時、 Employment#employee
に Engineer
のインスタンスをいれたらそのまま #employee_type
は Engineer
になるだろうな、なんて思っていると、全然そんなことはなく Employee
が入る。
当然、 source_type
を Engineer
にしている Company#engineers
も引けない。employee_type
がミスマッチでコケるから。
気をつけて。