单表继承rails has_many

时间:2013-10-25 05:09:20

标签: ruby-on-rails inheritance activerecord single-table-inheritance

我有一个名为Course的模型,需要与考试和作业相关联。我希望能够编写这样的代码:

>>c = Course.new
>>assignment1 = c.assignments << Assignment.new
>>exam1 = c.exams << Exam.new

c.assessments现在应包括exam1和assignment1

我认为应该如何实现(使用评估模型中的单表继承):

class Course < ActiveRecord::Base
  has_many :assessments
  attr_accessible :title, :name, :startDate, :endDate, :color
end

class Assessment < ActiveRecord::Base
  belongs_to :course
  attr_accessible :end_at, :name, :start_at, :type, :weight
end

class Assignment < Assessment
end

class Exam < Assessment
end

我已尽力了解如何做到这一点,但我似乎无法弄明白。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

课程只有评估关联,所以你应该能够编写这样的代码:

c = Course.new
c.assesments << Assignment.new
c.assesments << Exam.new

还要确保assesments表的type列具有数据类型字符串。