Skip to Main Content
Learning Rails
book

Learning Rails

by Simon St. Laurent, Edd Dumbill
November 2008
Beginner content levelBeginner
448 pages
12h 25m
English
O'Reilly Media, Inc.
Content preview from Learning Rails

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-3 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 a migration:

script/generate ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Rails 5

Learning Rails 5

J. Mark Locklear, Eric J Gruber, Barnabas Bulpett
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao
Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher

Publisher Resources

ISBN: 9780596154943Supplemental ContentErrata