Rails与名称空间

时间:2016-09-15 14:12:48

标签: ruby-on-rails ruby polymorphic-associations model-associations

我想保存不同的结果(默认和手动),每个结果都有原因。认为这将是多态关联的好地方。然而,这些模型是命名空间的,这是一个比预期更加诡异的方法。关注the guide

应用/模型/事件/ 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::EventReasonEvent::Result::EventReason

1 个答案:

答案 0 :(得分:8)

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

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

这样你就不会让rails试图从.event_reason中猜出你的类(在这种情况下它无法做到)。