我有一个用户模型,属于个人资料(belongs_to polymorphic)。一个模型有两个子类,但 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匹配子类而不是父类?
答案 0 :(得分:3)
这是因为_type
列应该标识模型的表,不应该包含模型本身的数据 - 只是一个参考。
但是,如果您检查user.profile.type
,则应返回SomeDeepProf1
。