Browse Source

Create Participants for new Members

Maarten van den Berg 8 years ago
parent
commit
8b73fc0444
2 changed files with 26 additions and 4 deletions
  1. 5 0
      app/models/group.rb
  2. 21 4
      app/models/member.rb

+ 5 - 0
app/models/group.rb

@@ -22,6 +22,11 @@ class Group < ApplicationRecord
22 22
     self.members.includes(:person).where(is_leader: true)
23 23
   end
24 24
 
25
+  # @return [Array<Activity>] the activities that haven't started yet.
26
+  def future_activities
27
+    self.activities.where('start > ?', DateTime.now)
28
+  end
29
+
25 30
   # Determine whether the passed person is a group leader.
26 31
   def is_leader?(person)
27 32
     Member.exists?(

+ 21 - 4
app/models/member.rb

@@ -8,6 +8,7 @@ class Member < ApplicationRecord
8 8
   belongs_to :person
9 9
   belongs_to :group
10 10
 
11
+  after_create   :create_future_participants!
11 12
   before_destroy :delete_future_participants!
12 13
 
13 14
   validates :person_id,
@@ -16,15 +17,31 @@ class Member < ApplicationRecord
16 17
       message: "is already a member of this group"
17 18
     }
18 19
 
20
+  # Create Participants for this Member for all the group's future activities, where the member isn't enrolled yet.
21
+  # Intended to be called after the member is added to the group.
22
+  def create_future_participants!
23
+    activities = self.group.future_activities
24
+
25
+    if not self.person.activities.empty?
26
+      activities = activities.where(
27
+        'activities.id NOT IN (?)', self.person.activities.ids
28
+      )
29
+    end
30
+
31
+    activities.each do |a|
32
+      Participant.create!(
33
+        activity: a,
34
+        person: self.person
35
+      )
36
+    end
37
+  end
38
+
19 39
   # Delete all Participants of this Member for Activities in the future.
20 40
   # Intended to be called before the member is deleted.
21 41
   def delete_future_participants!
22
-    activities = self.group.activities
23
-      .where('start > ?', DateTime.now)
24
-
25 42
     participants = Participant.where(
26 43
       person_id: self.person.id,
27
-      activity: activities
44
+      activity: self.group.future_activities
28 45
     )
29 46
 
30 47
     participants.each do |p|