Active Record可以通过多个模型进行操作

时间:2014-02-13 06:10:53

标签: activerecord ruby-on-rails-4

是否可以访问多个模型以外的对象?

例如,假设我有

class Contact <ActiveRecord:Base
 has_many :interactions
end

class Interaction <ActiveRecord:Base
 belongs_to :contact
 belongs_to :course_presentation 
end

class CoursePresentation <ActiveRecord:Base 
 has_many: interactions
 belongs_to :course
end

class Course <ActiveRecord:Base
 has_many :course_presentations
end

现在我知道我可以通过联系人写一个关于课程演示的直接关系,然后获得与所有课程演示相关的所有课程或者我可以做的

contact.interactions.map{ |i| i.course_presentation.course }

我希望能够直接提取与联系人相关的课程,例如

contact.courses

这可能吗?

1 个答案:

答案 0 :(得分:1)

是的,我相信。只需添加以下内容:

class Contact < ActiveRecord::Base
  has_many :interactions
  has_many :course_presentations, through: :interactions
  has_many :courses, through: :course_presentations
end