1

다른 결과 (기본 및 수동)를 저장하려는 경우 각 결과에 이유가있을 수 있습니다. 이것이 다형성 연관을위한 좋은 장소라고 생각했습니다. 그러나 모델은 네임 스페이스로되어 있으며 예상보다 까다로워졌습니다. 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::EventReason 그냥 Event::Result::EventReason

답변

5

당신은 중첩 될 수는 연결을 기대 보인다 연결시 class_name을 지정해야합니다.

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

이렇게하면 .event_reason (이 경우에는 할 수 없음)에서 레일을 시도하고 추측하도록 허용하지 않습니다.

+0

감사의 말! 남자 나는 문자 그대로 단지 같은 일을했다! 하이브 5. 이 얼마나 마음 트위스트 – TheLegend