我是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
有谁可以指出我做错了什么?
答案 0 :(得分:64)
在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
这就是假设你设置它的方式。
答案 1 :(得分:13)
您需要添加
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,然后添加直通。