Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 多态关联外部类型使用STI类将祖先类型设置为当前_Ruby On Rails_Ruby_Activerecord_Polymorphic Associations_Single Table Inheritance - Fatal编程技术网

Ruby on rails 多态关联外部类型使用STI类将祖先类型设置为当前

Ruby on rails 多态关联外部类型使用STI类将祖先类型设置为当前,ruby-on-rails,ruby,activerecord,polymorphic-associations,single-table-inheritance,Ruby On Rails,Ruby,Activerecord,Polymorphic Associations,Single Table Inheritance,我有 当我这样做的时候 class PageItem<ActiveRecord::Base belongs_to :itemable, :polymorphic=>true end 有人知道这件事吗 更新 根据bor1s的回答,这可能是正确的行为。因此,如果是,那么我的问题是如何将其隐式设置为Porsche?这是因为Porshe是虚拟模型,它实际上不存在于数据库中,它只有type字段才能知道它是Porshe。也许你应该去掉STI,使用saytype列保存Porshe类型的汽车模

我有

当我这样做的时候

class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end
有人知道这件事吗

更新


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

这是因为Porshe是虚拟模型,它实际上不存在于数据库中,它只有
type
字段才能知道它是Porshe。也许你应该去掉STI,使用say
type
列保存Porshe类型的汽车模型,并使用
scope
查找Porshe。我希望我能帮你一点忙。

我认为如果你在
Car
表中添加
type
字段,你将能够使用以下方法获得
保时捷
类型:
PageItem.new(:itemable=>Porsche.new).itemable.type

我想这就是STI继承的目的,对不同的类使用相同的表来存储。
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"