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

后端 未结 2 1494
感动是毒
感动是毒 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.

提交回复
热议问题