[英]Rails — How to setup model that can belong to either of 3 different models
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;"? 我是否应该为“: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 in diff models). 该问题将属于它们中的一个或几个或全部(因此我可以在diff模型中重用同一问题)。
Should I remove the :null=>false so it could belong to either of them....or what the best way to set that up? 我是否应该删除:null => false,以便它可以属于它们中的任何一个...。或者设置它的最佳方法是什么?
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. 我可能会为每个关系创建一个查找表,因此您将拥有一个exam_questions
, quiz_questions
和homework_questions
表。
Each of these would contain the id of the owner ( exam_id
for example), and the question ( question_id
). 其中每个都将包含所有者的ID(例如, exam_id
)和问题( 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. 如果您要引入新的所有者类型(例如studyguide
,这也使添加新关系变得非常容易。
You would leave the :null => false
in with this method, since a relationship will either exist or it won't. 您将使用此方法保留:null => false
,因为关系将存在或不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.