-1

I have an old rails project using Rails 2 . There is already model class Student. In database, there is a table students. Now, I need to implement that each student can have multiple courses. Which means I need to have a new table in database that's courses table & have one-to-many relationship from student to course.

How to create migration file to make this?

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38
Leem
  • 17,220
  • 36
  • 109
  • 159

2 Answers2

0

Rails 2 didn't have an option to create associations via the migration generator, so you have to take a more manual approach.

You can create the migration thusly: https://www.tutorialspoint.com/ruby-on-rails-2.1/rails-migrations.htm

You'll need to add the column student_id to your courses table with a column type of integer

Then add the following to your Student model:

has_many :courses

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38
0

This shouldn't be too difficult if you are actually using Rails 2.3

And TBH if you aren't AT LEAST on 2.3, then you should probably just recreate this project entirely...

1.) Use ruby script/generate model Course name:string description:text student_id:bigint to generate your migration, which should look something like this:

class CreateCourses < ActiveRecord::Migration
  def self.up
    create_table :courses do |t|
      t.string :name
      t.text :description
      t.bigint :student_id

      t.timestamps
    end
  end

  def self.down
    drop_table :courses
  end
end

2.) Find the newly created MODEL in your project directory with name course and add the association to the file:

belongs_to :student

3.) Find the STUDENT model in your project folder and add the has_many association to that:

has_many :students

4.) In your terminal, cd into your project folder and run rake db:migrate

You should be good to go after that! Here's the reference for Rails 2.3 associations: https://guides.rubyonrails.org/v2.3/association_basics.html

Danodemo
  • 61
  • 7