如何通过迁移将关联添加到已经创建的关系中?

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

我创建了 2 个 table studentsissued_books。但是忘记在迁移中添加 t.belongs_to :students,同时创建 issued_books table.

现在我修改了对应的模型为:

class Student < ActiveRecord::Base
has_many :issued_book
end

class IssuedBook < ActiveRecord::Base
belongs_to :student
end

我现在如何通过 rails 中的迁移来完成?

$ bin/rails generate migration AddUserRefToProducts user:references
generates

将生成以下内容:

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

来源:http://edgeguides.rubyonrails.org/active_record_migrations.html

所以在你的情况下会是:

$ bin/rails generate migration AddStudentRefToIssuedBooks student:references

您只需在 belongs_to 模型中填充 foreign_key

$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

这将在 issued_books 数据库中创建适当的列,这应该允许您引用其关联的 Student

Ref for t.belongs_to

--

您还应该考虑查找有关 table 结构范围的 has_many/belongs_to 关联: