Ruby on rails 如何查询Rails中ActiveRecord搜索返回的每个元素

Ruby on rails 如何查询Rails中ActiveRecord搜索返回的每个元素,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,假设我在Rails中有一个用户模型,它包含有许多:群组。然后,我的队列模型包含有很多:注册。当我跑步时: u.队列 返回的是 [#<Cohort id: 1, start_date: "2013-01-15", end_date: "2013-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 1, user_id: 2>, #<Cohort id:

假设我在Rails中有一个
用户
模型,它包含
有许多:群组
。然后,我的
队列
模型包含
有很多:注册
。当我跑步时:

u.队列

返回的是

[#<Cohort id: 1, start_date: "2013-01-15", end_date: "2013-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 1, user_id: 2>,
 #<Cohort id: 2, start_date: "2014-01-15", end_date: "2014-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 1, user_id: 2>,
 #<Cohort id: 3, start_date: "2013-01-15", end_date: "2013-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 2, user_id: 2>,
 #<Cohort id: 4, start_date: "2014-01-15", end_date: "2014-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 2, user_id: 2>,
 #<Cohort id: 5, start_date: "2013-01-15", end_date: "2013-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 3, user_id: 2>,
 #<Cohort id: 6, start_date: "2014-01-15", end_date: "2014-05-15", created_at: "2014-01-11 01:31:29", updated_at: "2014-01-11 01:31:29", course_id: 3, user_id: 2>]
[#,
#,
#,
#,
#,
#]

然后,我将如何从该队列列表中获取所有注册的列表?我试着做了
u.队列。登记
,但没有成功。我不想使用
has-many-through
关系。

has-many有什么问题:注册,:through=>:队列?这是一个非常自然的方法。否则,您可能必须执行以下操作:

enrollments = u.cohorts.map(&:enrollments).flatten
has_many :cohorts_enrollments, :through => :cohorts, :source => :enrollments
如果你看看这些背后的SQL,has_许多:through更好

由于您已经有一个has_many:注册,您可以使用以下内容定义另一个关系:

enrollments = u.cohorts.map(&:enrollments).flatten
has_many :cohorts_enrollments, :through => :cohorts, :source => :enrollments

查看has\u many上的选项:

我认为您可以添加
has\u many。。。通过
到用户模型

#User.rb
has_many :enrollments, through: :cohorts

# in your code
u.enrollments
我有两种类型的用户(使用cancan)——学生和教师。因此,我的用户模型中已经有了一个
和多个注册
,以支持有多个注册的学生。我现在想查找每个队列中的注册,以便教员可以查看所有学生注册。因为我已经有了一个
有很多注册
,我不认为我也能有一个
有很多:注册,:通过=>:队列
。我很想这么做,但我认为这是不可能的。可能吗?这种方法肯定更可取。