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

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

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