在 Rails 中找不到关联问题 [英] Could not find the association problem in Rails
问题描述
我是 Ruby on Rails 的新手,我显然有一个活动记录关联问题,但我无法自己解决.
I am fairly new to Ruby on Rails, and I clearly have an active record association problem, but I can't solve it on my own.
给定三个模型类及其关联:
Given the three model classes with their associations:
# 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
但是当我执行控制器向申请表添加问题时,出现错误:
But when I execute the controller to add questions to application forms, I get the error:
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
谁能指出我做错了什么?
Can anyone point out what I am doing wrong?
推荐答案
在ApplicationForm 类中,需要指定ApplicationForms 与'form_questions' 的关系.它还不知道.在您使用 :through
的任何地方,您都需要先告诉它在哪里可以找到该记录.你的其他课程也有同样的问题.
In the ApplicationForm class, you need to specify ApplicationForms's relationship to 'form_questions'. It doesn't know about it yet. Anywhere you use the :through
, you need to tell it where to find that record first. Same problem with your other classes.
所以
# 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
假设您就是这样设置的.
That is assuming that's how you have it set up.
这篇关于在 Rails 中找不到关联问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!