我有一个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
current_user.groups
是唯一组的集合,belong_to
是模型设置中的用户。