无法在Rails中找到关联问题

Ash*_*Ash 35 activerecord ruby-on-rails associations models

我是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
Run Code Online (Sandbox Code Playgroud)

但是当我执行控制器向应用程序表单添加问题时,我收到错误:

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
Run Code Online (Sandbox Code Playgroud)

谁能指出我做错了什么?

Jim*_*Jim 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
Run Code Online (Sandbox Code Playgroud)

这假设你是如何设置它的.


ben*_*sie 13

你需要包括一个

has_many :form_question_answers
Run Code Online (Sandbox Code Playgroud)

在您的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
Run Code Online (Sandbox Code Playgroud)

看起来您的架构可能有点不稳定,但重点是您始终需要首先为连接表添加has_many,然后添加直通.