Rails:处理几个类似的模型类? [英] Rails: Deal with several similar model classes?

查看:120
本文介绍了Rails:处理几个类似的模型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立课程申请系统。高中,本科和研究生均可申请本课程。他们必须填写一些申请表。



然而,他们的信息表格是相似的,但不完全一样。每个学生都有姓名,电话号码,电子邮箱,地址等。但只有本科生必须提供GPA,研究生需要告诉他们正在研究哪个实验室。还有其他微妙的区别...



那么我该怎么处理呢?做一张大桌子,但是让高中生的GPA栏留空?或者使用三个单独的表?



此外, Student 之间有一些关系(或者在三个表中, HighSchoolStudent 本科学生 GraduateStudent )和其他模型。例如,课程有许多学生 s,学生有许多问题 s等等。

解决方案

您可以使用 STI Store 功能实现这一点。



声明基本模型为学生,文本列称为设置

 班学生< ActiveRecord :: Base 
存储:设置
#名称,电子邮件,电话,地址等。
end


class HighSchool学生<学生
#声明HighSchool学生具体属性
store_accessor:设置,:gpa
end


class本科学生<学生
#声明本科学生特定属性
store_accessor:设置:attr1
end

class GraduateStudent<学生
#声明GraduateStudent具体属性
store_accessor:settings,:attr2
end

在上面的示例中, HighSchoolStudent 的实例将具有一个名为 gpa 的属性。


I'm building a course application system. The high school, undergraduate and graduate students are all able to apply for this course. They have to fill out some application form.

However, their information forms are similar, but not exactly the same. Every student has name, phone number, email, address, etc. But only undergraduate students have to provide their GPA, and graduate students is required to tell which lab they are researching at. There are other subtle differences...

So how should I deal with this? Make a big table, but leave 'GPA' column of high school students NULL? Or use three separate tables?

Moreover, there are some relation between Student(or, in three tables case, HighSchoolStudent, UndergraduateStudent and GraduateStudent) and other models. For instance, Course has many Students, Student has many Questions, and so on.

解决方案

You can use a combination of STI and Store feature achieve this.

Declare a base model for Student with a text column called settings.

class Student < ActiveRecord::Base
  store :settings
  # name, email, phone, address etc..
end


class HighSchoolStudent < Student
  # declare HighSchoolStudent specific attributes 
  store_accessor :settings, :gpa
end


class UndergraduateStudent < Student
  # declare UndergraduateStudent specific attributes 
  store_accessor :settings, :attr1
end

class GraduateStudent< Student
  # declare GraduateStudent specific attributes 
  store_accessor :settings, :attr2
end

In the sample above, instances of HighSchoolStudent will have an attribute called gpa.

这篇关于Rails:处理几个类似的模型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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