rails中的复合关键关联3

时间:2012-03-21 10:57:28

标签: ruby-on-rails ruby-on-rails-3

我的rails应用程序中有4个模型:

课堂/教师/学生/作业

我需要一个:

课堂与教师之间的关系 老师和学生之间的关系

对于这两种关系,这没关系,因为我将为has_and_belongs_to_many创建2次迁移。

对于Assignments模型,我需要将它与之前的3个模型相关联:

作业表应如下:
   - id
   - 标签
   - classroom_id
   - teacher_id
   - pupil_id

以下是最后一种关系模型化的最佳方法吗?

class Assignment < ActiveRecord::Base
  belongs_to: classroom
  belongs_to: teacher
  belongs_to: pupil
end

class classroom < ActiveRecord::Base
  has_many: assignments
end

class teacher < ActiveRecord::Base
  has_many: assignments
end

class pupils < ActiveRecord::Base
  has_many: assignments
end

1 个答案:

答案 0 :(得分:0)

考虑多态关联http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class Assignment < ActiveRecord::Base
  belongs_to: assignable, :polymorphic => true
end

class Classroom < ActiveRecord::Base
  has_many :assignment, :as => :assignable
end