1

I am building a multiple choice exam, which is better, to store each choice into choices table, and link them to the question, or just create an object which contains all the choices and question text, and store it serialized into DB as one record ??

If I chose the serialized object method, I will save my self thousands of choices records belonging to questions.

class Quiz < ActiveRecord::Base
  has_many :choices
end

class Choice < ActiveRecord::Base
  belongs_to :quiz
end

So, which method to consider ??

mu is too short
  • 426,620
  • 70
  • 833
  • 800
simo
  • 23,342
  • 38
  • 121
  • 218

1 Answers1

2

Use separate tables. Storing serialized data in a relational database is almost always a bad idea; if you start with a clean normalized schema, changes will be much easier in the future (and all software changes over time, especially "one off quick hacks").

In your case, you want the choices in a separate table so that you can easily answer questions like "how many people chose option 3 for question 8?" or "which questions only have 2 choices".

Having separate tables also makes referential integrity much easier. For example, you could set up taken_quizes which have many answers which have one answer_choices each; then you can link the answer_choices back to choices to avoid inconsistent data. Referential integrity is difficult and very expensive if you're storing serialized data structures in the database.

BTW, you seem to have forgotten your Question class: a Quiz has many Questions and each Question has many Choices.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • thanks mu, you've enlightened my way,could you please check my other question, related to the same topic: http://stackoverflow.com/questions/8102682/rails-3-1-how-to-calculate-answers-number-using-foreign-key – simo Nov 12 '11 at 07:44
  • hello mu, do you recommend to merge associated tables into the question table ? so that I have new fields like: choice1, choice2, choice3, choice4, of type string ?? will this be better design ? with respect to speed and performance ? – simo Nov 22 '11 at 15:29
  • @Samir: If you are absolutely certain that you'll only ever have four choices then four columns is a reasonable option; I'd probably go with a separate table though, then you could easily foreign key the responses back to the choice. The basic rule is to normalize everything as far as possible and then denormalize as necessary. You don't know where your performance problems will be until they happen; optimizing clean normalized code is easier than cleaning up prematurely optimized code. – mu is too short Nov 22 '11 at 18:25