我创建了2个表students
和issued_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中迁移来实现这一目标?
答案 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
。
-
您还应该考虑在表结构中查找has_many/belongs_to
关联范围: