Lets say I have two databases: one for students and one for classes. I would like to be able to ‘add’ classes to a specific student and also be able to add students to a specific class. I assume I need to use a join table here but I am a little lost on how to use them. I would ultimately like to be able to do something like:
@class.students.find(@student_id)
and this would tell me if the student is in the class or not. I know the relationship between classes and students is ‘has_many’ and vice versa. Does doing ‘t.references :students’ in the migrate files accomplish that? I tried adding that line to my migrate file and then tried finding something using the statement above and it gave me an error. I am new to RoR so I am not even sure what the best way to go about achieving this is. Any help is appreciated!
Yes, this is a many-to-many relationship (class has many students, student has many classes). For this you’ll use a
has_many :throughrelation. Take a look at the docs forActiveRecord::Associations(Ctrl-F for “Association Join Models”).In a migration,
t.references :studentsis how you would specify abelongs_torelation, as it just adds astudent_idcolumn (which can only accommodate one id, i.e. one student). A join model, however, will have two columns:student_idandclass_id. (Incidentally, calling a model ‘Class’ in Ruby is asking for trouble. Might I suggest ‘Course’?)