【问题标题】:Why doesn't my polymorphic_type field get assigned automatically by rails为什么我的 polymorphic_type 字段没有被 rails 自动分配
【发布时间】:2013-01-06 23:12:26
【问题描述】:

我将单表继承与多态关联结合使用。这是我的模型。

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 记录,其中填充了 type 字段,但是,未填充 eventable_type 字段(应该是 Race)。我的印象是 rails 会自动填充此字段,类似于 STI 类型字段。是我有错误的印象还是我的关联设置有问题。

感谢您的意见。

【问题讨论】:

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


    【解决方案1】:

    如果你只传入 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")
    

    【讨论】:

    • Beerlington - 感谢您的帮助。不知何故,我说服自己 Rails 可以从关联中找出类型,但经过进一步思考,我明白了问题所在。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2015-11-01
    • 2021-10-03
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多