Connecting Students to Awards
So, awards now have a basic understanding of the student records to which they connect. What can student records do with awards?
Removing Awards When Students Disappear
Although in reality, you might want to keep award listings around when students leave,
for demonstration purposes itâs worth considering the problem of orphaned records.
The validates_existence_of
plug-in described earlier
can check that a corresponding student record exists at the time the award record is
created, but once the record has been created, validation doesnât notice, for
example, if the student is deleted. Keeping award records in sync with student records
requires something more active.
Rails makes it very easy to make sure that when student records are deleted, the
corresponding awards records are also deleted. You just need to add an option to the
has_many
declaration in app/models/student.rb:
has_many :awards, :dependent => :destroy
This is powerful and easy, but beware: those deletions will take place without any further confirmation. Once the user agrees to delete a student record, all of the awards records connected to that student will also disappear.
Counting Awards for Students
While adding the awards list to the main list of students could get really verbose, it does make sense to add a count of awards received to the list of students. If you add the set of awards listed in Figure B-3 of Appendix B, youâll have an awards list like that shown in Figure 9-5.
Adding ...
Get Learning Rails: Live Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.