Determine if children have been added / removed in the Rails callback

Scenario:

I have a habtm relationship and you want to determine if children have been added or removed in one direction. I try to use callbacks, but found that I do not have a change record for children. Is there something like course.students.changed?


Using:

  • Rails 3.0.3
  • Ruby 1.9.2p0

Tables:

students - id, first_name, last_name
courses - id, name, location
courses_students - course_id, student_id


Models:

class Course # Callbacks before_save :student_maintenance # Relationships has_and_belongs_to_many :students protected def student_maintenance # I want to do something like students.changed? students.changes.each do |student| if marked_for_deletion # do something elsif marked_for_addition # do something else end end end end end class Student # Relationships has_and_belongs_to_many :courses end 
+4
source share
2 answers

If you want to capture when a student has been added or removed from a course, why not use the class for the join * courses_students * table? Since this is the place where the record will actually be created or destroyed, you can easily use subsequent after_create / after_destroy callbacks.

+2
source

As is the case with the polar answer - but perhaps a little more explanation:

In textual UML terms, the relationship can be this:

 Course ------*-> Student 

Read: The course has from 0 to many students.

You can add and remove students from the association as you wish.

However, you are interested in learning more about the association, that is, when the student was added or removed from the course. This "additional" association information reveals the need to use another class, aka "Class Association".

So, now you must insert this class between your existing classes in such a way as to allow yourself to call it "Registration":

 Course ------*->Registration------1->Student 

Read: The course has from 0 to many registrations. Each registration must have exactly 1 student.

The registration class may look like this:

 +--------------+ | Registration | +--------------| | student | | time_added | | time_dropped | +--------------+ 

This way, you can easily get a list of current students for the course (where time_dropped is zero). Or a list of students who left (where time_dropped is not zero).

0
source

Source: https://habr.com/ru/post/1334567/


All Articles