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

后端 未结 2 1493
感动是毒
感动是毒 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 12:56

    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:

    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 will need to add two fields to your Question model:

    assessment_id
    assessment_type
    

    With this relationship, you can use it like:

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

    and it will know exactly which questions belong to which model based on the additional fields in your question model.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题