How can I insert data into a table using migration, and this table is generated earlier through another migration

I have a role table with username, role and company. I want to insert data into this table through a new migration file, so how to do it?

I have such code, but how can I use it and where can I not understand.

class Foo < ActiveRecord::Migration
  def self.up
    Users.new(:username => "Hello", :role => "Admin")
  end
  def self.down
    Users.delete_all(:username => "Hello")
  end
end
+3
source share
2 answers

It:

Users.new(:username => "Hello", :role => "Admin")

does not insert data into your table. It just creates a user object. To insert data, you must call savefor the created object:

Users.new(:username => "Hello", :role => "Admin").save

Or better yet, use createinstead new:

Users.create(:username => "Hello", :role => "Admin")
+6
source

It seems that you are using this database migration solely to populate the data.

, ( , , - , ). . rails api - migrations.

, , :

rake db:rollback
... Edit the previous migration ..Add the code to populate
rake db:migrate

, . railscast .

: :

db/seeds.rb
:

['Sampath', 'Suresh'].each do |name|
  User.create(role: 'admin', username: name)
end

rake db:seed

seeds.rb .

+2

All Articles