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

时间:2016-02-02 11:15:53

标签: ruby-on-rails activerecord associations

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

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

class Student < ActiveRecord::Base
has_many :issued_book
end

class IssuedBook < ActiveRecord::Base
belongs_to :student
end

如何通过在rails中迁移来实现这一目标?

2 个答案:

答案 0 :(得分:1)

$ 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

答案 1 :(得分:0)

您只需填充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 db中创建相应的列,这样您就可以使用它来引用其关联的Student

Ref for t.belongs_to

-

您还应该考虑在表结构中查找has_many/belongs_to关联范围:

enter image description here