0

我在两个表之间有许多多对多关系,条件表示不同的角色。

class Course < ActiveRecord::Base
  ...
  has_many :course_mentors, :conditions => { :type_str => "mentor" }, :class_name => CourseUser
  has_many :mentors, :through => :course_mentors, :source => :user

  has_many :course_enrollees, :conditions => { :type_str => "enrollee" }, :class_name => CourseUser
  has_many :enrollees, :through => :course_enrollees, :source => :user
  ...
end

要单独检索其中一个关联的内容,我可以简单地执行@course.enrollees、@course.mentors 等。但有时将登记者和导师聚集在一起会很方便。

我有许多不同的关联,这使得为单个关联的每个组合创建额外的关联是不切实际的。总能做到

(@course.enrollees + @course.mentors).sort

但是,这会导致对数据库的两次请求,并可能导致重复条目。

我还研究了merge关联函数,但是这只是返回一个空关系。

这样做的最好的rails方式是什么?

4

1 回答 1

4

您可以在 Course 模型中简单地为 CourseUser 添加一般关联:

has_many :course_users

然后在 CourseUser 模型中放置一个范围:

scope :of_type, lambda {|types| where(:type_str => types)}

然后您可以通过以下方式访问它:

my_course = Course.first
my_course.course_users.of_type([:mentor, :enrollee])
于 2012-10-29T15:45:59.303 回答