0

캠프에 캠핑을 등록하는 레일 앱을 개발 중입니다. 먼저 이름, 이메일 등을 사용하여 가입하십시오. 프로필이 작성되면 캠프에 등록 할 수 있습니다. 캠프가 아직 가득 차 있지 않은 경우 즉시 등록됩니다. 가득 찬 경우 대기자 명단에 올립니다. 지금 저는 캠핑 (이름, 이메일 등), 캠프 (이름, 위치 등), 등록 및 대기자라는 4 가지 모델이 있습니다. 아이디어는 야영자가 많은 야영장에 등록 할 수있게하는 것이고, 분명히 많은 야영자를 등록하거나 대기자 명단에 대기시키는 야영장이 될 수 있습니다. 수업 내용은 다음과 같습니다.레일 - 동일한 모델에 여러 개의 'has_many through'연관이 있음

# camper.rb 
has_many :enrolled_in, :class_name => 'Camps', through: :enrollments, dependent: :destroy 
has_many :waitlisted_in, :class_name => 'Camps', through: :waitlists, dependent: :destroy 

# camp.rb 
has_many :enrolled_campers, :class_name => 'Camper', through: :enrollments 
has_many :waitlisted_campers, :class_name => 'Camper', through: :waitlists 

보기를 통해 이러한 모델에 액세스하는 데 문제가 있습니다. 여기 show.html.erb의 모습입니다 :

<!-- Listing camps --> 
<h2>Camps</h2> 
<p> 
    <strong>Name:</strong> 
    <%= @camper.enrolled_in.name %> <!-- This is where I get the error --> 
</p> 

<!-- Adding camps --> 
<h2>Add a camp:</h2> 
<%= form_with(model: [@camper, @camper.enrolled_in.build ]) do |form| %> 
<p> 
    <%= form.label :name %><br> 
    <%= form.text_field :name %> 
</p> 
<p> 
    <%= form.submit %> 
</p> 
<% end %> 

그러나 나는 다음과 같은 오류 받고 있어요 :

ActiveRecord::HasManyThroughSourceAssociationNotFoundError in Campers#show

Could not find the source association(s) "enrolled_in" or :enrolled_in in model Enrollment. Try 'has_many :enrolled_in, :through => :enrollments, :source => '. Is it one of camp or camper?

을 그리고 솔직히 잘못 무슨 일이 일어나고 있는지 알 수 없습니다. 나는 데이터베이스와 레일에 상당히 익숙하다.

답변

0

HABTM 연관의 방향을 살펴보십시오.

  1. 이렇게하면 코드가 더 깨끗해집니다. after_add과 :
  2. 당신은해야합니다. (같은 이름의 has_many 콜백 달리, 심지어 외국인 직접 키 삽입)는 항상 모델의 변경 사항을 추적합니다 after_destroy 작업을

겠어요 -

class Camper 
    has_and_belongs_to_many :waitlists, after_add: :check_camp_ready_to_start_as_example 
    has_and_belongs_to_many :enrolllists 
end 

class Waitlist 
    belongs_to :camp 
    has_and_belongs_to_many :campers 
end 

class Enrolllist 
    belongs_to :camp 
    has_and_belongs_to_many :campers 
end 

class Campl 
    has_many :enrolllists 
    has_many :waitlists 
end 

등의 마이그레이션을 만드는 방법 당신이 읽을 수 (테이블을 조인 작성해야합니다) here