问题
I have a role table with user name and role and company. I want to insert data into that table through a new migration file so how can i do this?
I got a code like this but how can i use it and where i am not able to 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
回答1:
This:
Users.new(:username => "Hello", :role => "Admin")
does not insert data into your table. It merely creates a user object. To insert the data you have to call save
on the object you create:
Users.new(:username => "Hello", :role => "Admin").save
Or better yet, use create
instead of new
:
Users.create(:username => "Hello", :role => "Admin")
回答2:
It appears that you are using this database migration solely for populating the data.
Database migrations are meant for changing the database schema, not for populating the database (though you can add some logic to populate the database after the change; for example, if you add a column - role to users table, you can add some custom logic to populate the newly added field for existing entries in users table). Refer to rails api - migrations for details.
If you forgot add the code to populate the database in your previous database migration, you can undo the previous migration and apply it again using:
rake db:rollback
... Edit the previous migration ..Add the code to populate
rake db:migrate
If you just want to populate the database, you should seed the database instead. Watch this railscast for more information.
EDIT: To seed the database:
Create a file called db/seeds.rb
Add the record creation code like this:
['Sampath', 'Suresh'].each do |name|
User.create(role: 'admin', username: name)
end
Then,
rake db:seed
This will read the seeds.rb and populate the database.
来源:https://stackoverflow.com/questions/10534682/how-can-i-insert-data-into-table-by-the-help-of-migration-and-that-table-is-gene