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
Everything true what @Jordan said, here the concrete steps to take:
rails g model CourseStudent creates a join model for the n:m relation, and the migration to the corresponding table.Edit the migration file CreateCourseStudent so it contains the following:
class CreateCourseStudent < ActiveRecord::Migration
def change
create_table :course_students do |t|
# Your code comes here
t.integer :student_id
t.integer :course_id
# Here comes the generated code
t.timestamps
end
end
end
Run the migration: rake db:migrate. As a result, the join table should now exist in your database.
Add to the models the following code
class Course < ActiveRecord::Base
has_many :course_students
has_many :students, :through => :course_students
end
class Student < ActiveRecord::Base
has_many :course_students
has_many :courses, :through => :course_students
end
class CourseStudent < ActiveRecord::Base
belongs_to :student
belongs_to :course
end
You are now able to use the methods generated by the methods belongs_to and has_many:
@course.students@student.coursesTry to find all the relevant facts and snippets in the Rails Guides, there you should find all information you need to get on track. Good luck!