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

Ruby on rails 如何通过迁移将关联添加到已经创建的关系中?,ruby-on-rails,activerecord,associations,Ruby On Rails,Activerecord,Associations,我已经创建了两个表学生和发行的书籍。但在创建已发行图书表时,忘记在迁移中添加t.attown\u to:students 现在,我将相应的模型修改为: class Student < ActiveRecord::Base has_many :issued_book end class IssuedBook < ActiveRecord::Base belongs_to :student end class-Student

我已经创建了两个表
学生
发行的书籍
。但在创建
已发行图书
表时,忘记在迁移中添加
t.attown\u to:students

现在,我将相应的模型修改为:

class Student < ActiveRecord::Base
has_many :issued_book
end

class IssuedBook < ActiveRecord::Base
belongs_to :student
end
class-Student
我现在如何通过在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

您只需在您的
模型中填充以下内容:

$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
$rails g migration AddForeignKeyToIssuedBook
#db/migrate.rb
类AddForeignKeyToIssuedBook学生id
结束
结束
结束
$rake数据库:迁移
这将在
发行的\u图书
db中创建相应的列,您可以通过该列引用与其关联的
学生

--

您还应该考虑查找表结构上的作用域关联:

$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