【问题标题】:Polymorphic association foreign_type sets ancestor type instead current, using STI class多态关联 foreign_type 使用 STI 类设置祖先类型而不是当前类型
【发布时间】:2011-08-18 14:25:54
【问题描述】:

我有

class Car < ActiveRecord::Base; end

class Porsche < Car
  has_many :page_items, :as=>:itemable, :dependent=>:destroy
end

我必须提到我正在使用一个名为 cars 的表,其中有一个字段 type

class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end

当我这样做时

  a = PageItem.new
  a.itemable = Porsche.new
  a.itemable
  #<Porsche id: nil, type: "Porsche", name: nil, ..etc>

  a.itemable_type
  => "Car"

应该是的

  a.itemable_type
  => "Porsche"

有人知道吗?

更新

根据bor1s 的回答,这可能是正确的行为。所以如果是这样,那么我的问题是如何将其隐式设置为Porsche

【问题讨论】:

    标签: ruby-on-rails ruby activerecord polymorphic-associations single-table-inheritance


    【解决方案1】:

    这是因为Porshe是virtual模型,它并不真正存在于数据库中,它只是有type字段知道它是Porshe。也许你应该摆脱 STI 并使用 type 列来保存类型为 Porshe 的汽车模型,并使用 scope 来查找 porshes。希望对你有所帮助。

    【讨论】:

    • 嗯,我猜这就是 STI 继承的目的,为不同的类使用同一个表来存储。
    【解决方案2】:

    我认为如果您将type 字段添加到Car 表中,您将能够使用以下方法获得Porsche 类型: PageItem.new(:itemable =&gt; Porsche.new).itemable.type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 2016-05-21
      • 2014-06-23
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多