1

我有一个用户模型,它属于Profile(belongs_to 多态)。一个模型有两个子类,但User中的profile_type始终对应于父模型。

User < ActiveRecord::Base
  belongs_to :profile, :polymorphic => true

SomeProf < ActiveRecord::Base
  has_one :user, :as => :profile

SomeDeepProf1 < SomeProf

SomeDeepProf2 < SomeProf

然后:

sdp1 = SomeDeepProf1.new
user = sdp1.create_user
user.profile_type
> 'SomeProf'

即使在子类中声明关联,profile_type仍然是SomeProf

为什么会这样?有什么方法 profile_type 匹配子类而不是父类?

4

1 回答 1

3

发生这种情况是因为该_type列应该标识模型的表,并且不应该包含模型本身的数据 - 只是一个参考。

但是,如果您检查user.profile.type它应该返回SomeDeepProf1.

于 2010-02-12T15:23:04.703 回答