Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add some inserts in rails migration?

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

thanks

like image 294
xaver23 Avatar asked Apr 19 '10 13:04

xaver23


People also ask

Can you edit a migration file Rails?

If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.

How do you go down a particular migration in Rails?

To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.


2 Answers

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)" 
like image 178
Ryan McGeary Avatar answered Oct 03 '22 23:10

Ryan McGeary


Update: This is the right answer: https://stackoverflow.com/a/2667747/7852


Here's an example from 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 
like image 43
Ju Nogueira Avatar answered Oct 03 '22 22:10

Ju Nogueira