我将单表继承与多态关联结合使用。这是我的模特。
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)。我认为rails会自动填充此字段,类似于STI类型字段。我是否有错误的印象,或者我的关联设置是否存在问题。
感谢您的投入。
答案 0 :(得分:4)
如果您只是传递了eventable_id,它将如何知道它是什么类型?您必须传递整个可事件对象或基于track_condition_changes关系构建它:
<强> 1。传递可事件对象:
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")