Rails -- 如何设置可以属于 3 个不同模型中的任何一个的模型
我正在尝试制作一个应用程序,它可以进行类似于您在学校中经历的测试。
我有一个模型问题,它可以属于考试、测验或作业。
我应该为“:exam_id, :integer, :null => false; :quiz_id, :integer, :null => false; :assignment_id, :integer, :null => false;”创建字段吗?
该问题将属于其中一个或几个或全部(因此我可以在差异模型中重复使用相同的问题)。
我应该删除 :null=>false 以便它可以属于它们中的任何一个......或者设置它的最佳方法是什么?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您想要在这里做的是使用多态关系。您需要为考试/测验/作业指定一个通用名称,每个问题都属于其中一个。假设您将它们称为“评估”,您将像这样设置您的模型:
然后您需要将两个字段添加到您的问题模型中:
有了这种关系,您可以像这样使用它:
并且它将确切地知道哪些问题属于哪个模型关于问题模型中的其他字段。
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:
Then you will need to add two fields to your Question model:
With this relationship, you can use it like:
and it will know exactly which questions belong to which model based on the additional fields in your question model.
我可能会为每个关系创建一个查找表,这样您就会有一个
exam_questions
、quiz_questions
和homework_questions
表。其中每个都包含所有者的 ID(例如
exam_id
)和问题(question_id
)。这样,如果一个问题仅属于三个关系中的一个或两个,您只需为这些关系创建行。如果您要引入新的所有者类型(例如
studyguide
等),这也使得添加新关系变得非常容易。您将保留
:null =>; false
在此方法中,因为关系要么存在,要么不存在。I would probably create a look up table for each relationship, so you would have an
exam_questions
,quiz_questions
, andhomework_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.