Chapter 9. Developing Model Relationships

Everything you’ve done so far has been in the context of an application with one and only one table. That’s actually enough power to run a lot of different projects, from contact managers to time-series data collection. However, you’ll quickly find that most of the projects for which it’s worth creating a web application require more than just one table. Fortunately, Rails makes that easy, giving you the tools you need to create multiple tables and manage even complex relationships between them.


If you don’t know much about databases, now is a good time to visit Appendix B. Up to this point, it’s been possible to largely forget that there was a relational database underneath the application, except for some mechanics. From this point on, you’ll need to understand how tables work in order to understand how Rails models work. (You still don’t need to understand SQL, however.)

Working with multiple tables is, on the surface, pretty simple. Every Rails model maps to a table, so working with multiple tables just means working with multiple models. The hard part is managing the relationships between the tables—which in Rails demands managing the relationships between models.

Most of the steps for working with multiple models are the same as for working with single models, just done once for each table. Once the models are created, though, the real work begins. Some of it can be done easily and declaratively, while other parts require thinking ...

Get Learning Rails now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.