Take the following simple object model for example:
class Course
has_many :enrollments
has_many :students, :through => :enrollments, :after_add => :send_email
def send_email(student)
puts "Email Sent"
end
end
class Enrollment
belongs_to :course
belongs_to :student
end
class Student
has_many :enrollments
has_many :courses, :through => :enrollments
end
I would like to perform send_email
after one or more Students are added to a Course, however after_add is fired after each item is added to the students collection.
bill = Student.first
carl = Student.last
Course.first.students << [bill, carl]
Will output
Email Sent
Email Sent
How can I catch a SINGLE event after ALL items are added to a collection?
Is it possible to insert records into the enrollments
table in a single query for all students rather than one per student?
Does Rails have any built in mechanism or do I need to write custom logic to catch then batch flush calls to send_email
?
Thanks for any information!