Rya*_*ary 87
不要.如果您正在寻找种子数据,您应该使用db/seeds.rb而rake db:seed不是.  更多信息在这个Railscast中.
附注:始终确保代码db/seeds.rb是幂等的.即重新运行种子应始终是安全的.
但是,如果必须在迁移中插入或修改数据,则最好使用SQL语句.在未来的应用程序版本中,不保证您的模型类仍以相同的形式存在,如果直接引用模型类,将来从头开始运行迁移可能会产生错误.
execute "insert into system_settings (name, label, value) values ('notice', 'Use notice?', 1)"
Ju *_*ira 10
更新: 这是正确答案: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
小智 5
编辑:请注意 - 上面的海报是正确的,您不应该在迁移中填充数据库.不要使用它来添加新数据,只是在更改架构时修改数据.
对于很多东西,使用原始SQL会更好,但是如果你需要在迁移过程中插入数据(例如,在将表分成多个表时进行数据转换),并且你想要一些默认的AR东西,比如方便的数据库-independent escaping,您可以定义模型类的本地版本:
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/