Using join tables in ruby on rails

前端 未结 3 1679
难免孤独
难免孤独 2020-12-04 16:43

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

3条回答
  •  庸人自扰
    2020-12-04 17:25

    Yes, this is a many-to-many relationship (class has many students, student has many classes). For this you'll use a has_many :through relation. Take a look at the docs for ActiveRecord::Associations (Ctrl-F for "Association Join Models").

    In a migration, t.references :students is how you would specify a belongs_to relation, as it just adds a student_id column (which can only accommodate one id, i.e. one student). A join model, however, will have two columns: student_id and class_id. (Incidentally, calling a model 'Class' in Ruby is asking for trouble. Might I suggest 'Course'?)

提交回复
热议问题