So, awards now have a basic understanding of the student records to which they connect. What can student records do with awards?
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.
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 of these awards to the students list that’s in
app/views/students/index.html.erb is
simple. There needs to be a new column for awards, so at the end of
the first row (in the first tr
element), add:
<th>Awards</th>
And then, after:
<td><%=h student.start_date %></td>
add:
<td><%=h student.awards.count %></td>
Just as every award
object
now has a student
object because of belongs_to
, every student
object has an awards
object, thanks to the has_many
declaration. Getting a count of
awards for that student is as simple as specifying count
. Figure 9-6 shows the
results of these additions.
You’ll probably want to format them more beautifully, but the
basic data is there. It also makes sense to add a list of awards to
each of the individual student views, so that users can see what
students have won as they review the records. Thanks to the awards
method, it isn’t difficult to add an
awards table to app/views/students/show.html.erb:
<h3>Awards</h3>
<table>
<tr>
<th>Name</th>
<th>Year</th>
<th>Student</th>
</tr>
<% for award in @student.awards %>
<tr>
<td><%=h award.name %></td>
<td><%=h award.year %></td>
<td><%=h award.student.name %></td>
</tr>
<% end %>
</table>
In the view, the @student
variable contains the current student. Running a for
loop over the collection returned by
@student.awards
, which contains
only the awards for the current student, lets you put the information
about the awards into a table. You’ll get a result like that shown in
Figure 9-7.