Rails:通过迁移填充现有表 [英] Rails: populate an existing table via a migration
问题描述
假设我在Rails中已有迁移:
Say I have an existing migration in Rails:
class CreateStudies < ActiveRecord::Migration
def change
create_table :studies do |t|
t.string :display_name, null: false
t.string :tag_name, null: false
t.timestamps
end
add_index :studies, :tag_name, unique: true
end
end
稍后,我意识到我想在此表中填充许多行,并且我不想使用rake db:rollback
或seeds.rb文件.新迁移文件的格式是什么?
Later on I realise that I would like to populate this table with a number of rows and I don't want to use rake db:rollback
or the seeds.rb file. What is the format of the new migration file?
推荐答案
刚刚:
在命令提示符下生成:
rails generate migration AddInitialStudies
并修改up
和down
生成的迁移方法:
And modify up
and down
method of generated migration:
class AddInitialStudies < ActiveRecord::Migration
def up
Study.create(display_name: "Example name", tag_name: "example_name")
end
def down
Study.delete_all
end
end
目前,我生成了一个Study对象,但是您可以添加任意数量的对象.
At this point I generate one Study object, but you can add as many you want.
在down
上,删除在up
上添加的记录,因为回滚和再次迁移将复制添加的记录.我假设唯一的研究记录是在up
上创建的.注意:tag_name
,它必须是唯一的.
On down
, remove records added on up
, because rollback and migrate again will duplicate added records. I assume the only Study records are the created on up
. Take care with :tag_name
, which must be unique.
这篇关于Rails:通过迁移填充现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!