has_many_polymorphs的意思是“参照完整性违规”?

时间:2009-08-05 20:39:39

标签: ruby-on-rails ruby activerecord has-many-polymorphs

我在has_many_polymorphs和许多不同类型的事件之间存在Candidate关系。特别是,Candidate在创建时会创建Created事件。

class Candidate < ActiveRecord::Base
  has_many_polymorphs :events, :through => :candidate_events,
                               :from => Event::Base.included_in_classes.map { |klass|
                                 klass.to_s.underscore.pluralize.to_sym
                               })
  after_validation_on_create :create_created_event

  private
  def create_creation_event
    Event::Created.create!(:candidate => self, :creator => creator)
  end
end

class CandidateEvent < ActiveRecord::Base
  belongs_to :candidate
  belongs_to :event, :polymorphic => true
end

module Event::Base
  ...
end

class Event::Created < ActiveRecord::Base
  include Event::Base
  validates_presence_of :creator
end

当我进行单元测试时,一切都很好。当我运行我的功能测试时,一切都很好。当我运行我的集成(Cucumber)测试时,一切都很好。当我在生产中运行时,一切都很好。当我尝试在开发模式下运行(启用类重载)时,我得到了

Referential integrity violation; child <Event::Created:1> was not found for :events.
Expected record['candidate_events.event_id'] (1) to be equal to record['created_events.id'] ().
  {
    "candidate_events.event_type"=>"Event::Created",
    "candidate_events.created_at"=>"2009-08-05 20:28:31",
    "candidate_events.updated_at"=>"2009-08-05 20:28:31",
    "candidate_events.candidate_id"=>"1",
    "candidate_events.event_id"=>"1",
    "candidate_events.id"=>"1"
  }

在同一个(开发)环境中运行script/console我看到Event::Created对象与CandidateEvent交叉引用模型有正确关系。

发生了什么事?

1 个答案:

答案 0 :(得分:2)

我们可以确定Event :: Base.included_in_classes在重新加载类时返回正确的类吗?这种技巧不依赖于加载顺序吗?也许Event :: Created尚未包含Event :: Base?