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,â ...
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.