I'm trying to make an app that does testing similiar to what you would experience in school.
I have a model Question, which can belong to either an Exam, Quiz, or Assignment.
Should I create fields for ":exam_id, :integer, :null => false; :quiz_id, :integer, :null => false; :assignment_id, :integer, :null => false;"?
The question will belong to either one or a few or all of them ( so i can reuse the same question in diff models).
Should I remove the :null=>false so it could belong to either of them....or what the best way to set that up?
It sounds like what you want to do here is use a polymorphic relationship. You will need a generic name for exam/quiz/assignment and each question will belong to one of these. Say you call them Assessments, you would set up your models like this:
Then you will need to add two fields to your Question model:
With this relationship, you can use it like:
and it will know exactly which questions belong to which model based on the additional fields in your question model.
I would probably create a look up table for each relationship, so you would have an
exam_questions
,quiz_questions
, andhomework_questions
table.Each of these would contain the id of the owner (
exam_id
for example), and the question (question_id
).This way if a question belonged to only or two of the three, you could just create rows for those relationships. This also makes it very easy to add new relationships if you were to introduce a new owner type, like
studyguide
or something.You would leave the
:null => false
in with this method, since a relationship will either exist or it won't.