After creating a table (by migration), I want to insert some entries directly. How must I write a migration for this?
thanks
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.
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.
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)"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With