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

查看:108
本文介绍了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;"?

问题将属于其中一个或几个或全部(因此我可以在diff模型中重用相同的问题) 。

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

然后,您需要向您的Question模型中添加两​​个字段: / p>

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天全站免登陆