Rails 名称为 space 的多态关联

Rails Polymorphic associations with name space

我想保存不同的结果(默认和手动),每个结果都可以有一个原因。认为这将是多态关联的好地方。然而,模型是命名空间的,事实证明这比预期的要复杂。正在关注 the guide

app/models/event/reason.rb

#  id              :integer          not null, primary key
#  reasons         :string
#  reasonable_id   :integer
#  reasonable_type :string
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#

class Event::Reason < ActiveRecord::Base
  belongs_to :reasonable, polymorphic: true
end

app/models/event/result.rb

class Event::Result < ActiveRecord::Base
  belongs_to :event
  has_one :event_reason, as: :reasonable
end

app/models/event/manual_result.rb

class Event::ManualResult < ActiveRecord::Base
  belongs_to :event
  has_one :event_reason, as: :reasonable
end

但如果我尝试做类似的事情:

Event::ManualResult.last.event_reason
  Event::ManualResult Load (5.1ms)  SELECT  "event_manual_results".* FROM "event_manual_results"  ORDER BY "event_manual_results"."id" DESC LIMIT 1
  NameError: uninitialized constant Event::ManualResult::EventReason

 Event::Result.last.event_reason
   Event::Result Load (0.4ms)  SELECT  "event_results".* FROM "event_results"  ORDER BY "event_results"."id" DESC LIMIT 1
   NameError: uninitialized constant Event::Result::EventReason

似乎期望关联嵌套在附加层中 Event::ManualResult::EventReasonEvent::Result::EventReason

您只需要在关联上指定class_name:

class Event::Result < ActiveRecord::Base
  belongs_to :event
  has_one :event_reason, as: :reasonable, class_name: 'Event::Reason'
end

这样你就不允许 rails 尝试从 .event_reason 为你猜测 class(在这种情况下无法做到)。