Rails:处理几个类似的模型类? [英] Rails: Deal with several similar model classes?
问题描述
然而,他们的信息表格是相似的,但不完全一样。每个学生都有姓名,电话号码,电子邮箱,地址等。但只有本科生必须提供GPA,研究生需要告诉他们正在研究哪个实验室。还有其他微妙的区别...
那么我该怎么处理呢?做一张大桌子,但是让高中生的GPA栏留空?或者使用三个单独的表?
此外, Student
之间有一些关系(或者在三个表中, HighSchoolStudent
,本科学生
和 GraduateStudent
)和其他模型。例如,课程
有许多学生
s,学生
有许多问题
s等等。
声明基本模型为学生
,文本列称为设置
。
班学生< 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 Student
s, Student
has many Question
s, 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屋!