rails中的继承和多态关联 [英] Inheritance and polymorphic-associations in 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屋!