How do I add some inserts in rails migration?

后端 未结 5 1134
说谎
说谎 2020-12-04 23:47

After creating a table (by migration), I want to insert some entries directly. How must I write a migration for this?

thanks

5条回答
  •  抹茶落季
    2020-12-05 00:44

    Don't. If you're looking for seed data, you should use db/seeds.rb and rake db:seed instead. More info in this Railscast.

    Side note: Always make sure that the code in db/seeds.rb is idempotent. i.e. It should always be safe to re-run your seeds.

    But, if you must insert or modify data inside a migration (there are legitimate use-cases for this), it's best to use SQL statements instead. Your model class isn't guaranteed to still be around in the same form in a future version of your application, and running the migrations from scratch in the future might yield errors if you reference the model class directly.

    execute "insert into system_settings (name, label, value) values ('notice', 'Use notice?', 1)"
    

提交回复
热议问题