/
memberships.rb
75 lines (61 loc) · 2.54 KB
/
memberships.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#
# This module contains the methods of the User model regarding the associated
# user group memberships and groups.
#
module UserMixins::Memberships
extend ActiveSupport::Concern
included do
# User Group Memberships
# ==========================================================================================
# This associates all UserGroupMembership objects of the group, including indirect
# memberships.
#
has_many( :memberships,
-> { where(ancestor_type: 'Group', descendant_type: 'User') },
class_name: 'UserGroupMembership',
foreign_key: :descendant_id )
# This associates all memberships of the group that are direct, i.e. direct
# parent_group-child_user memberships.
#
has_many( :direct_memberships,
-> { where(ancestor_type: 'Group', descendant_type: 'User', direct: true) },
class_name: 'UserGroupMembership',
foreign_key: :descendant_id )
# This associates all memberships of the group that are indirect, i.e.
# ancestor_group-descendant_user memberships, where groups are between the
# ancestor_group and the descendant_user.
#
has_many( :indirect_memberships,
-> { where(ancestor_type: 'Group', descendant_type: 'User', direct: false) },
class_name: 'UserGroupMembership',
foreign_key: :descendant_id )
# This returns the membership of the user in the given group if existant.
#
def membership_in( group )
memberships.where(ancestor_id: group.id).limit(1).first
end
# Groups the user is member of
# ==========================================================================================
# This associates the groups the user is member of, direct as well as indirect.
#
has_many(:groups,
-> { where('dag_links.descendant_type' => 'User').uniq },
through: :memberships,
source: :ancestor, source_type: 'Group'
)
# This associates only the direct groups.
#
has_many(:direct_groups,
-> { where('dag_links.descendant_type' => 'User', 'dag_links.direct' => true).uniq },
through: :direct_memberships,
source: :ancestor, source_type: 'Group'
)
# This associates only the indirect groups.
#
has_many(:indirect_groups,
-> { where('dag_links.descendant_type' => 'User', 'dag_links.direct' => false).uniq },
through: :indirect_memberships,
source: :ancestor, source_type: 'Group'
)
end
end