Nesting Awards in Students

The connections between students and awards are workable, but the way that the two models are handled by the web application doesn’t reflect their actual roles in the data models. Depending on your application and your preferences, this may be perfectly acceptable. There is, however, a better way to represent the awards model that more clearly reflects its relationship to students, implemented in ch09/students002.

The models will stay the same, and the views will stay almost the same. The main things that will change are the routing and the controller logic. Chapter 13 will explain routing in much greater depth, but for now it’s worth exploring the ways that routing can reflect the relationships of your data models.

Note

If the work involved in creating a nested resource seems overwhelming, don’t worry. It’s not mandatory Rails practice, though it is certainly a best practice. Unfortunately, it’s just complicated enough that it’s hard to automate—but maybe someday this will all disappear into a friendlier script/generate command.

Changing the Routing

Near the top of the config/routes.rb file are the lines:

map.resources :awards

map.resources :students

Delete them, and replace them with:

map.resources :students, :has_many => [ :awards ]

It’s another has_many relationship, which is this time expressed as a parameter to map.resources. You don’t need to specify the belongs_to relationship. Yes, this is kind of a violation of “Don’t Repeat Yourself,” but at the same ...

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.