Не удалось найти проблему с ассоциацией в Rails
Я новичок в 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
Может ли кто-нибудь указать, что я делаю неправильно?
Ответы
Ответ 1
В классе ApplicationForm вам необходимо указать отношение ApplicationForms к 'form_questions'. Он еще не знает об этом. В любом месте, где вы используете :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
Это предполагает, что вы настроили его.
Ответ 2
Вам нужно включить
has_many :form_question_answers
В вашей модели FormQuestion.: Через ожидает таблицу, которая уже была объявлена в модели.
То же самое касается других моделей - вы не можете предоставить ассоциацию 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 для таблицы join, а затем добавить сквозную.