【问题标题】:Multiple choice quiz app in railsRails 中的多项选择测验应用程序
【发布时间】:2018-03-08 22:44:19
【问题描述】:

我正在尝试构建一个 Rails 测验应用程序,其中会有一个问题,该特定问题将有 4 个选择。以下是我对模型的处理方法:

rails g Question description:text choice:array

我无法开始。这是正确的方法吗?如果不是,我该怎么办?

然后会有类别模型,因为它与问题模型有 has_many 关联。

rails g Category name:string 

我将在问题表中存储类别外键以显示此问题来自此特定类别。

我对设计正确的问题模型感到震惊。非常感谢您的帮助

【问题讨论】:

  • 当我构建这种东西时,我会选择一个具有 question_id 的单独对象。我发现通常需要用到的东西是:文本、资源(vid/img)、正确或不正确(布尔),可能还有一个整数来排序选择,然后是 question_id 引用。然后是一个问题has_many 选择和一个选择belongs_to 问题。然后,您可以循环选择问题。只是我发现构建 2 个电子学习系统的想法很有效。
  • 您会为选择列分配什么数据类型?考虑到我必须为 Choice 创建一个单独的模型。
  • 我不会在问题表中放置选择列。您不需要它,只需在模型中设置关系,以便选择属于_一个问题和一个问题有_许多选择。选择表需要一个 question_id 参考。
  • 是的,我的意思是像你说的那样不同的模型rails g model Choice name: ..。如果这是你建议做的。您会为选项名称分配什么数据类型?因为每个问题都应该有 4 个选项。
  • 没有名字,就像text:text, correct:boolean,position:integer``question:references。我使用 gemacts_as_list 这就是为什么我使用position:integer 来订购它们,如果顺序无关紧要,你不需要它。所以一个选项有文本,它是否正确,它在该问题的所有选项的顺序中有一个位置(如果你需要对它们进行排序),它引用了它所属的一个问题。

标签: ruby-on-rails


【解决方案1】:

您应该考虑一个额外的答案模型。好的,我们走吧:

问题:

# == Schema Information
#
# Table name: questions
#
#  id               :integer          not null, primary key
#  question_text    :text
#  type             :string
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class Question < ActiveRecord::Base
  has_many :answer_options, dependent: :destroy # the questions choices
end

答案选项:

# == Schema Information
#
# Table name: answer_options
#
#  id             :integer          not null, primary key
#  answer_text    :text
#  question_id    :integer
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#
class AnswerOption < ActiveRecord::Base
   belongs_to :question
   validates :answer_text, presence: true, allow_blank: false
end

如何存储用户答案?在另一个模型中,我们称之为 question_answer 。 -> 用户的回答。用户选择了一些 answer_options -> 我们将这些 ID 存储在序列化的 answer_option_ids 属性中。

# == Schema Information
#
# Table name: question_answers
#
#  id                        :integer          not null, primary key
#  question_id               :integer
#  answer_option_ids         :text
#  user_id                   :integer
#

class QuestionAnswer < ActiveRecord::Base
  serialize :answer_option_ids
  belongs_to :question
  belongs_to :user
  validates_presence_of :question_id, :user_id
end

在您的 question.rb 中添加 has_many :question_answers, dependent: :destroy 以获得该问题的答案

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2021-10-21
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多