37

我对 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

谁能指出我做错了什么?

4

2 回答 2

72

在 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

那是假设你是这样设置的。

于 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 回答