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

有人能指出我做错了什么吗?

推荐答案

在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

这是假设你是这样设置的.

Ruby-on-rails相关问答推荐

Rails 7 Active Record::SessionStore -如何获取控制器中当前会话的数据库ID?

Rails:has_many 通过不返回结果

has_many 通过大小验证

这种使用on:的语法在 Ruby on Rails 中意味着什么?

计算总价(商品数量*商品价格)

Rails Scope 返回 all 而不是 nil

Ruby/Rails 中的类方法与常量

在 Rails 中将毫秒转换为格式化日期

如何判断是否已经在 ruby​​ on rails 的数据库事务中?

如何让 Rspec 运行嵌套在文件夹下的所有测试?

安装mysql2(0.4.8)时出错,Bundler无法继续

rails 模型 has_many 本身

如何在 RoR 中实现成就系统

在 PostgreSQL 中强制字符串的最大长度

未选中时,如何使 check_box_tag 发布false或0参数?

通过重定向使闪存哈希保持不变

Ruby 和 Ruby on Rails 离线 API 文档

Ruby on Rails - link_to 按钮 / css

ActiveRecord 中多列的索引

您可以在弹性 beantalk 环境中运行 rails 控制台或 rake 命令吗?