Rails -- 如何设置可以属于 3 个不同模型之一的模型 [英] Rails -- How to setup model that can belong to either of 3 different models

查看:23
本文介绍了Rails -- 如何设置可以属于 3 个不同模型之一的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个应用程序,它可以进行类似于您在学校体验的测试.

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.

我应该为:exam_id, :integer, :null => false; :quiz_id, :integer, :null => false; :assignment_id, :integer, :null => false;"创建字段吗?

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).

我是否应该删除 :null=>false 以便它可能属于其中任何一个....或者设置它的最佳方法是什么?

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.

这篇关于Rails -- 如何设置可以属于 3 个不同模型之一的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆