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,使用saytype
列保存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"