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
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.
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
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:
:has_many => [ :awards ]
has_many relationship, which is
this time expressed as a parameter to
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 ...