开发者

Database design question (RAILS)

I have a quiz application. Which follows a normal pattern of database development

Quiz --> QuizQuestions --> QuizQuestionChoices

QuizAttempt --> QuizAttemptAnswer

In quiz_attempt_answers I store the answer as a string instead of a reference to QuizQuestionChoices for the following reason.

  1. If the question gets dele开发者_运维知识库ted from the quiz (maybe it the quiz gets revised), we don't want to lose what they put in.
  2. If the choices get changed or rearranged, we want to have the answer they chose

Are these valid reasons for NOT using a foreign key for the answer?


I would continue with your approach but store the association as well.

So...

class QuizQuestionChoice < ActiveRecord::Base
  has_many :quiz_attempt_answers, :dependent => :nullify
end

class QuizAttemptAnswer < ActiveRecord::Base
  belongs_to :quiz_question_choice
end

That way if a QuizQuestionChoice is deleted the foreign_key is set to null AND you still have their actual answer.

There are cases where you may even store the original question with the answer. In case somebody changes the wording which unintentionally changes the meaning of it.


Just to answer your last question, they aren't particularly valid reasons but only because there are a number of good alternatives. Of course, it always depends on your situation, how you plan to use the data in the future, how simple it is to implement an alternative, and so on and so forth...

What lebreeze suggested is definitely a feasible option. Another solution would be to simply store the quiz_question_choice_id on quiz_attempt_answers and add an active flag on the quiz_question_choices that marks a choice inactive when it's removed from a question - it adds a bit of overhead when manipulating quizzes, however it keeps your associations in tact. Then, when displaying quizzes, you would just filter out the inactive options from the answer choice list. The main reason I suggest this is for cohesive data, so that if say a year from now a business requirement comes up that wants to know statistics such as "how many people answered this question with choice X?", you will have everything you need to write such reports.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜