2009-11-23 13 views
31

Ruby on Railsの新機能ですが、私は明らかにアクティブなレコード関連の問題がありますが、私自身で解決することはできません。Railsで関連付けの問題が見つかりません

その団体との3つのモデルクラスを考える:

# 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

私はこれを何千回もやったことがありますし、私の他の働くhmtモデルを見ても、私が他のhas_many ... LOLを見逃しているのを見ることができませんでした... – Danny

11

あなたのFormQuestionモデルで

has_many :form_question_answers 

を含める必要があります。 :throughは、モデルですでに宣言されているテーブルを期待しています。同じ

あなたの他のモデルのために行く - あなたはhas_many :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 

を宣言するまで、あなたのスキーマが少しグラグラかもしれないように見えますが、ポイントは、最初にjoinテーブルのhas_manyを追加してから、throughを追加する必要があります。

+0

これは本当にありがとうございます - あなたはもちろん、あなたの答えにスポットを当てます。しかし、「そこには1つしかない」ということで、最初に答えたので、他の人に答えを与えました。私はあなたの答えを投票したので、正解を持っていることに少なくとも慰安賞がありました。ありがとう。 :) – Ash

関連する問題