Rails 测验应用程序的正确模型关联

Proper model associations for a Rails quiz app

我正在开发一个 rails 应用程序来进行测验。我有三种用于创建测验的模型:测验、问题和选​​择。一个小测验有问题,问题有多个选择,有一个选择是正确的。

关系如下:

Quiz 
belongs_to: course

Question
belongs_to: quiz
has_many: choices

Choice
belongs_to: question

我有 C++ 背景,我用 C++ 构建它的方式是进行测验 class 和问题 class。我不会为了选择而制作一个完整的 class,因为它们只需要保存一个字符串(选择)以及它是否是正确的选择。我的问题是,我什至需要有一个选择模型吗?

是的,您需要一个 Choice 模型。但是你需要更正 association in Question model

#Question
belongs_to :quiz
has_many :choices #as question will have many choices provided
belongs_to :examination

Rails 一开始联想可能很棘手。说 belongs_to 表示 is the child of,就像 has_one 表示 is the parent of one。我会推荐如下结构:

Course
has_many :quizzes

Quiz 
belongs_to :course
has_many :questions

Question
belongs_to :quiz
has_many :choices

Choice
belongs_to :question

当您创建关联时,这意味着您通过子关联上的 object_id 将两个表关联在一起。大多数表(如果不是全部)都有一个附带的模型。创建迁移时(Ruby 类 有助于创建架构),请务必正确包含必要的关联和外键。

可在此处找到有关协会的更多信息:Rails Guides: Active Record Associations

但是,有了这些关联,您就不能为另一个问题重复使用一个选项。也就是说,我的意思是您 可以 使用相同的字符串创建另一个选择对象,但它将具有不同的 id。要指定一个选择是否正确,您可以将 correct 属性标志设置为 truefalse。由于选项已经有 question_id,您可以确定它们会正确显示在考试结果中!

您可以在此处查找迁移:Rails Guides: Active Record Migrations