如何从另一个ActiveRecord对象集合中获取ActiveRecord对象的集合?

时间:2015-04-09 13:32:02

标签: ruby-on-rails ruby activerecord

我有一个ActiveRecord集合:

current_user.memberships
=> [#<Membership id: 20, student_id: 19, group_id: 4, state: "accepted", created_at: "2015-04-02 09:58:45", updated_at: "2015-04-02 09:59:42">,
 #<Membership id: 19, student_id: 18, group_id: 4, state: "accepted", created_at: "2015-03-19 14:01:58", updated_at: "2015-03-20 13:27:38">,
 #<Membership id: 17, student_id: 16, group_id: 4, state: "accepted", created_at: "2015-03-19 13:42:38", updated_at: "2015-03-20 13:28:38">,
 #<Membership id: 16, student_id: 15, group_id: 4, state: "accepted", created_at: "2015-03-19 13:39:15", updated_at: "2015-03-19 13:39:15">,
 #<Membership id: 15, student_id: 14, group_id: 4, state: "accepted", created_at: "2015-03-19 13:28:12", updated_at: "2015-03-19 13:28:12">,
 #<Membership id: 14, student_id: 13, group_id: 4, state: "accepted", created_at: "2015-03-19 13:26:44", updated_at: "2015-03-19 13:26:44">,
 #<Membership id: 13, student_id: 12, group_id: 4, state: "accepted", created_at: "2015-03-19 13:19:05", updated_at: "2015-03-19 13:19:05">]

我希望从current_user.memberships获取群组(唯一)。在这种情况下,只有一个Group

#<Group id: 4, school_id: 6538, name: "Klasa 1a", created_at: "2015-03-19 13:19:05", updated_at: "2015-03-19 13:19:05", user_id: 13, tutor_user_id: nil, tutor_email: nil>

在伪代码中,类似于current_user.memberships.groups.unique。我怎么能这样做?

我的模特:

class Group < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :groups
  has_many :memberships, through: :groups
end

class Membership < ActiveRecord::Base
  belongs_to :student
  belongs_to :group
end

1 个答案:

答案 0 :(得分:0)

current_user.groups是模型设置中belong_to用户的唯一群组的集合。