Reputation: 1425
I am trying to build a rails quiz app, where there will be a question and that particular question will have 4 choices. And below is my approach to the model:
rails g Question description:text choice:array
I am having trouble getting started. Would this be right approach? If not how should I go about this?
And then there will be category model as which will have has_many association with Question model.
rails g Category name:string
I will be storing categories foreign key in questions table to show this question is from this particular category.
I am struck at designing the proper Question model. Help would be much appreciated
Upvotes: 0
Views: 2096
Reputation: 2727
You should think of an extra answer model. OK let's go:
Question:
# == 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
AnswerOption:
# == 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
How to store user answers ? In another model, let us call it a question_answer . -> the answer of an user. User selected some answer_options -> we store these IDs in serialized answer_option_ids attribute.
# == 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
in your question.rb add has_many :question_answers, dependent: :destroy
to get answers to that question
Upvotes: 2