Rails — How to setup model that can belong to either of 3 different models

后端 未结 2 1512
感动是毒
感动是毒 2021-01-03 12:52

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 A

2条回答
  •  醉话见心
    2021-01-03 13:16

    I would probably create a look up table for each relationship, so you would have an exam_questions, quiz_questions, and homework_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.

提交回复
热议问题