views:

74

answers:

3

Hi

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

thanks

+1  A: 

create a new migration file like 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

OR

while creating table

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

Ref:- http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Salil
A: 

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
j.
+6  A: 

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 or this ASCIIcast.

But, if you must insert or modify data inside a migration, 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)"
Ryan McGeary
Exactly what I was writing. The written out version of the Railscast is here: http://asciicasts.com/episodes/179-seed-data
Benjamin Oakes