1

我使用单表继承与多态关联。这是我的模特。为什么我的polymorphic_type字段不能被rails自动分配

class ChangeInformation < ActiveRecord::Base 
    belongs_to :eventable, :polymorphic => true 
end 

class Race < ActiveRecord::Base 
    has_many :track_condition_changes, :as => :eventable, :class_name => "ChangeInformation" 
    #other associations omitted 
end 

class TrackConditionChange < ChangeInformation 

end 

的change_informations表具有以下字段:

type    #sti field 
change_code 
eventalbe_id  #polymorphic id 
eventable_type  #polymorphic type 
description 

当我使用下面的创建方法:

TrackConditionChange.create(:change_code => 1, :eventable_id => 3 :description => "test") 

一个TrackConditionChange记录被创建,以填充类型字段,但是,eventable_type字段(应该是Race)不会被填充。我的印象是铁轨填充这个字段自动类似于STI类型字段。我是否有错误的印象,或者我的关联设置有问题。

感谢您的意见。

回答

4

如果您只传递eventable_id,它将如何知道它是什么类型?你将不得不要么通过整个eventable对象或建立它的基础上的track_condition_changes关系:

1.传eventable对象:

race = Race.find(3) 
TrackConditionChange.create(:change_code => 1, :eventable => race, :description => "test") 

2.建立和基于关系的保存:

race = Race.find(3) 
race.track_condition_changes << TrackConditionChange.new(:change_code => 1, :description => "test") 
+0

Beerlington - 感谢您的帮助。不知怎的,我坚信自己的轨道可以从协会中找出类型,但经过进一步思考,我发现问题出在哪里。再次感谢! – Mutuelinvestor

相关问题