Vaishali Rajput
Vaishali Rajput

Reputation: 53

How to add association to relations, that are already created , through migration?

I have created 2 table students and issued_books. but forgot to add t.belongs_to :students in migration, while creating issued_books table.

Now I have modified the corresponding model as:

class Student < ActiveRecord::Base
has_many :issued_book
end

class IssuedBook < ActiveRecord::Base
belongs_to :student
end

How would I do it now through migration in rails?

Upvotes: 3

Views: 1334

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You just have to populate the foreign_key in your belongs_to model:

$rails g migration AddForeignKeyToIssuedBook

#db/migrate.rb
class AddForeignKeyToIssuedBook < ActiveRecord::Migration
   def change
      change_table :issued_books do |t| 
         t.belongs_to :student #-> student_id
      end
   end
end

$rake db:migrate

This will create the appropriate column in the issued_books db, which should allow you to reference its associated Student with it.

Ref for t.belongs_to

--

You should also consider looking up about has_many/belongs_to associations for scope on the table structure:

enter image description here

Upvotes: 0

Laurens
Laurens

Reputation: 2420

$ bin/rails generate migration AddUserRefToProducts user:references
generates

will generate the following:

class AddUserRefToProducts < ActiveRecord::Migration[5.0]
  def change
    add_reference :products, :user, index: true, foreign_key: true
  end
end

source: http://edgeguides.rubyonrails.org/active_record_migrations.html

So in your case it would be:

$ bin/rails generate migration AddStudentRefToIssuedBooks student:references

Upvotes: 5

Related Questions