Rails - How to set up a model that can belong to any of three different models

I'm trying to make an application that conducts testing similar to what you experienced at school.

I have a Question model that can belong to either an Exam, Quiz, or an Assignment.

Should I create fields for :: exam_id ,: integer ,: null => false ;: quiz_id ,: integer ,: null => false ;: assign_id ,: integer ,: null => false; "?

The question will belong to one or more or all of them (so I can reuse the same question in diff models).

Should I remove: null => false so that it can belong to any of them ... or what is the best way to set this?

+2
source share
2 answers

It looks like you want to use polymorphic relationships here. You will need a common name for the exam / quiz / assignment, and each question will belong to one of them. Let's say you call them "Ratings", you should set up your models as follows:

class Question << ActiveRecord::Base belongs_to :assessment, :polymorphic => true end class Exam << ActiveRecord::Base has_many :questions, :as => :assessment end class Quiz << ActiveRecord::Base has_many :questions, :as => :assessment end class Assignment << ActiveRecord::Base has_many :questions, :as => :assessment end 

Then you need to add two fields to your question model:

 assessment_id assessment_type 

Using this link, you can use it as:

 @exam = Exam.create({:field1 => :val1}) @exam.questions.create({:field1 => :question1}) @exam.questions.create({:field1 => :question2}) 

and he knows exactly which questions relate to which model, based on additional fields in your question model.

+5
source

I would probably create a lookup table for each link, so you have an exam_questions , quiz_questions and homework_questions table.

Each of them will contain an owner identifier (for example, exam_id ) and a question ( question_id ).

Thus, if the question belonged to only one or two of the three, you could simply create strings for this relationship. It also makes it easier to add new relationships if you need to introduce a new type of owner, such as studyguide or something else.

You will leave :null => false in this method, since relations will either exist or will not.

0
source

All Articles