O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 a count ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required