我想保存不同的结果(默认和手动),每个结果都有原因.认为这将是多态关联的好地方.然而,这些模型是命名空间的,这是一个比预期更加诡异的方法.在 the guide之后 应用程序/模型/事件/ r
应用程序/模型/事件/ 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
应用程序/模型/事件/ result.rb
class Event::Result < ActiveRecord::Base belongs_to :event has_one :event_reason, as: :reasonable end
应用程序/模型/事件/ 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 :: EventReason和Event :: 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中猜出你的类(在这种情况下它无法做到).