简介
假设我们要开发一个教学系统,那么老师和学生必然是系统不可缺少的两个model,要建立他们之间的映射,我们的数据库可能看起来是下面这个样子:
但是随着系统的开发,我们发现还需要将课程管理也纳入进来,于是数据库就变成了这个样子:
但是这样的数据库模型明显的不够DRY,因为teachers_students和teachers_courses两个表不但字段相似,完成的功能也是相同的,那么可不可以将它们合并呢?
答案是:可以。
使用evan weaver的has_many_polymorphs插件可以很轻松的完成这个任务。
安装
$ script/plugin install -x svn://rubyforge.org/var/svn/fauna/has_many_polymorphs/trunk
使用
对于上例,应用has_many_polymorphs后,我们的数据库看起来是这个样子:
修改app/models/teacher.rb
class Teaching < ActiveRecord::Base
belongs_to :teacher
belongs_to :teachable, polymorphic => trues
end
class Teacher < ActiveRecord::Base
has_many_polymorphs :teachables,
:from => [:students, :courses],
:through => :teachings
end
这就搞定了,不需要修改student.rb和course.rb,现在你可以这样使用teacher了:
teacher.teachables # 老师教授的所有课程及学生
teacher.students # 老师教授的所有学生
teacher.courses # 老师教授的所有课程
teacher.students[0].teacher # 老师自己
更多信息请参看使用手册。
数据库模型图使用DbDesigner绘制。
