rails中的继承和多态关联 [英] Inheritance and polymorphic-associations in rails

查看:131
本文介绍了rails中的继承和多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户模型,属于个人资料(belongs_to polymorphic)。一个模型有两个子类,但 User 中的 profile_type 始终对应于父模型。

I have a User model, which belongs to Profile (belongs_to polymorphic). One model comes in two subclasses, but the profile_type in User always correspond to the parent model.

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

Even stating the association in subclasses, the profile_type remains SomeProf.

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

Why does this happen? Is there any way profile_type match subclass and not the parent class?

推荐答案

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

This happens because the _type column is supposed to identify the model's table and should not contain data on the model itself - just a reference.

但是如果你检查 user.profile.type 它应返回 SomeDeepProf1

However if you inspect user.profile.type it should return SomeDeepProf1.

这篇关于rails中的继承和多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆