2009-11-23 2 views
31

저는 Ruby on Rails를 처음 사용하고 있으며 활성 레코드 연관성 문제가 분명합니다.하지만 직접 해결할 수는 없습니다.레일에서 연관 문제를 찾을 수 없습니다.

자신 협회와 함께 세 가지 모델 클래스를 감안할 때 :

# application_form.rb 
class ApplicationForm < ActiveRecord::Base 
    has_many :questions, :through => :form_questions 
end 

# question.rb 
class Question < ActiveRecord::Base 
    belongs_to :section 
    has_many :application_forms, :through => :form_questions 
end 

# form_question.rb 
class FormQuestion < ActiveRecord::Base 
    belongs_to :question 
    belongs_to :application_form 
    belongs_to :question_type 
    has_many :answers, :through => :form_question_answers 
end 

하지만 신청서에 질문을 추가 할 수있는 컨트롤러를 실행할 때, 나는 오류 얻을 :

ActiveRecord::HasManyThroughAssociationNotFoundError in Application_forms#show 

Showing app/views/application_forms/show.html.erb where line #9 raised: 

Could not find the association :form_questions in model ApplicationForm 

사람이 지적 할 수 무엇 내가 잘못하고있는거야?

답변

57

ApplicationForm 클래스에서 'form_questions'에 대한 ApplicationForms의 관계를 지정해야합니다. 그것은 아직 그것에 대해 모른다. :through을 사용하는 곳이면 먼저 해당 레코드를 찾을 위치를 지정해야합니다. 다른 수업에도 같은 문제가 있습니다.

은 그래서 가정한다

# application_form.rb 
class ApplicationForm < ActiveRecord::Base 
    has_many :form_questions 
    has_many :questions, :through => :form_questions 
end 

# question.rb 
class Question < ActiveRecord::Base 
    belongs_to :section 
    has_many :form_questions 
    has_many :application_forms, :through => :form_questions 
end 

# form_question.rb 
class FormQuestion < ActiveRecord::Base 
    belongs_to :question 
    belongs_to :application_form 
    belongs_to :question_type 
    has_many :form_questions_answers 
    has_many :answers, :through => :form_question_answers 
end 

당신이 사용자가 설정 한 방법입니다.

+1

나는 이것을 1000 번이나했는데 심지어 다른 내 작업하는 hmt 모델을 쳐다 보면서 다른 has_many ... LOL이 누락 된 것을 볼 수 없었다 ... – Danny

11

당신은 당신의 FormQuestion 모델의

has_many :form_question_answers 

을 포함해야합니다. : through 모델에서 이미 선언 된 테이블을 기대합니다. 먼저 스키마가 조금 남았습니다 수 있습니다처럼이 보이는 has_many

# application_form.rb 
class ApplicationForm < ActiveRecord::Base 
    has_many :form_questions 
    has_many :questions, :through => :form_questions 
end 

# question.rb 
class Question < ActiveRecord::Base 
    belongs_to :section 
    has_many :form_questions 
    has_many :application_forms, :through => :form_questions 
end 

# form_question.rb 
class FormQuestion < ActiveRecord::Base 
    belongs_to :question 
    belongs_to :application_form 
    belongs_to :question_type 
    has_many :form_question_answers 
    has_many :answers, :through => :form_question_answers 
end 

를 선언 할 때까지 당신이 has_many :through 연결을 제공 할 수는 없지만, 포인트입니다 -

동일은 다른 모델에 간다 먼저 join 테이블에 has_many를 추가 한 다음 through를 추가해야합니다.

+0

정말 고마워요. 물론 답장을 받으십시오. 그러나 "오직 하나만있을 수 있습니다."그래서 그는 먼저 대답했기 때문에 다른 사람에게 답을주었습니다. 나는 당신의 대답을 투표에 올려 놓았으므로 정답을 가졌음에도 적어도 위로 상이있었습니다. 고마워. :) – Ash