【发布时间】:2011-02-09 16:31:06
【问题描述】:
创建表后(通过迁移),我想直接插入一些条目。我必须如何为此编写迁移?
谢谢
【问题讨论】:
创建表后(通过迁移),我想直接插入一些条目。我必须如何为此编写迁移?
谢谢
【问题讨论】:
不要。如果您正在寻找种子数据,您应该使用db/seeds.rb 和rake db:seed。 More info in this Railscast.
旁注:始终确保db/seeds.rb 中的代码是幂等的。即重新运行种子应该始终是安全的。
但是,如果您必须在迁移中插入或修改数据(有合法的用例),最好改用 SQL 语句。不保证您的模型类在您的应用程序的未来版本中仍然以相同的形式存在,并且如果您直接引用模型类,将来从头开始运行迁移可能会产生错误。
execute "insert into system_settings (name, label, value) values ('notice', 'Use notice?', 1)"
【讨论】:
更新: 这是正确答案:https://stackoverflow.com/a/2667747/7852
这是来自ruby on rails api的示例:
class AddSystemSettings < ActiveRecord::Migration
# create the table
def self.up
create_table :system_settings do |t|
t.string :name
t.string :label
t.text :value
t.string :type
t.integer :position
end
# populate the table
SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
end
def self.down
drop_table :system_settings
end
end
【讨论】:
编辑:请注意 - 上面的海报是正确的,您不应该在迁移中填充数据库。不要使用它来添加新数据,仅用于修改数据作为更改架构的一部分。
在很多情况下,使用原始 SQL 会更好,但如果您需要在迁移过程中插入数据(例如,在将一个表拆分为多个表时进行数据转换),并且您需要一些默认的 AR 内容像方便的独立于 DB 的转义一样,您可以定义模型类的本地版本:
class MyMigrationSucksALittle < ActiveRecord::Migration
class MyModel < ActiveRecord::Base
# empty guard class, guaranteed to have basic AR behavior
end
### My Migration Stuff Here
### ...
end
请注意,这最适用于简单的情况;由于新类位于不同的命名空间 (MyMigrationSucksALittle::MyModel),因此在保护模型中声明的多态关联将无法正常工作。
可用选项的更详细概述位于此处:http://railsguides.net/2014/01/30/change-data-in-migrations-like-a-boss/
【讨论】:
创建一个新的迁移文件,例如 047_add_rows_in_system_settings.rb
class AddRowsInAddSystemSettings < ActiveRecord::Migration
def self.up
SystemSetting.create{:name => "name1", :label => "Use notice?", :value => 1}
SystemSetting.create{:name => "name2", :label => "Use notice?", :value => 2}
end
def self.down
SystemSetting.delete_all
end
end
或
创建表时
046_system_settings.rb
class AddSystemSettings < ActiveRecord::Migration
def self.up
create_table :system_settings do |t|
t.string :name
t.string :label
t.text :value
t.string :type
t.integer :position
end
SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
end
def self.down
drop_table :system_settings
end
end
参考:-http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
【讨论】: