开发者

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

开发者 https://www.devze.com 2023-01-12 08:07 出处:网络
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.

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 开发者_StackOverflow中文版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:

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消