Many-to-Many: Connecting Students to Courses

The other frequent relationship between tables or models is many-to-many. A student, for example, can be taking zero or more courses, while a course can have zero or more students. (Students with zero courses might not yet have registered for anything, while courses with zero students might be awaiting registration or just unpopular.)

The relationship between the two is, from a modeling standpoint, even, so there won’t be any need for nested resources, just a lot of connections. As usual, it makes sense to move up from the database through models to controllers and views to produce the code in ch09/students003. And also as usual, while Rails provides you with a foundation, you’re still going to need to add a lot to that foundation.

Warning

Remember, don’t name a table “classes,” or you will have all kinds of strange Rails disasters because of name conflicts. “Courses” is a safer option.

Creating Tables

Building a many-to-many relationship requires creating tables—not just a single table, but a many-to-many relationship that will require adding two tables beyond the student table already in the application. One will be the actual course list, and the other the table that joins courses to students, as shown in Figure B-5 of Appendix B. Creating the course list—which will need a full set of scaffolding—is simple:

script/generate scaffold course name:string

Creating the join table requires an extra few steps. Start by creating ...

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.