37

私は Ruby on 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

誰かが私が間違っていることを指摘できますか?

4

2 に答える 2

72

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

それはあなたがそれをどのように設定したかを前提としています。

于 2009-11-23T05:27:33.273 に答える
15

含める必要があります

has_many :form_question_answers

FormQuestion モデルで。: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

スキーマが少し不安定なように見えますが、ポイントは常に最初に結合テーブルの has_many を追加し、次にスルーを追加する必要があるということです。

于 2009-11-23T05:21:31.360 に答える