【问题标题】:Inheritance and polymorphic-associations in railsRails 中的继承和多态关联
【发布时间】:2010-02-12 15:16:48
【问题描述】:

我有一个 User 模型,它属于 Profile(属于多态)。一个模型有两个子类,但 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 匹配子类而不是父类?

【问题讨论】:

    标签: ruby-on-rails inheritance polymorphic-associations


    【解决方案1】:

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

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

    【讨论】:

    • 是的,马塞尔,我注意到了。我的代码使用 profile_type 来决定用户的类型并避免对数据库的额外访问。谢谢你的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多