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 ??
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_quizeswhich have manyanswerswhich have oneanswer_choiceseach; then you can link theanswer_choicesback tochoicesto 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.