Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Rails: How to populate Db with data without migrations getting in the way?
- $ rails new example -d mysql
- $ cd example/
- $ rails generate scaffold Users username:string password:string
- invoke active_record
- create db/migrate/20111004022310_create_users.rb
- create app/models/user.rb
- ...
- ...
- $ rake db:setup
- /Sites/example/db/schema.rb doesn't exist yet. Run
- "rake db:migrate" to create it then try again. If
- you do not intend to use a database, you should
- instead alter /Sites/example/config/application.rb
- to limit the frameworks that will be loaded
- $ rake db:migrate
- == CreateUsers: migrating ====================================================
- -- create_table(:users)
- -> 0.2389s
- == CreateUsers: migrated (0.2390s) ===========================================
- $ rake db:setup
- -- create_table("users", {:force=>true})
- -> 0.1460s
- -- initialize_schema_migrations_table()
- -> 0.5908s
- -- assume_migrated_upto_version(20111004022310, "db/migrate")
- -> 0.0010s
- $ rails console
- ruby-1.9.2-p180 :007 > u = User.new(:username => 'test', :password => 'testing?')
- => #<User id: nil, username: "test", password: "testing?", created_at: nil, updated_at: nil>
- ruby-1.9.2-p180 :008 > u.save!
- => true
- ruby-1.9.2-p180 :009 > User.all
- => [#<User id: 2, username: "test", password: "testing?", created_at: "2011-10-04 02:33:56", updated_at: "2011-10-04 02:33:56">]
- $ cat db/migrate/20111004022310_create_users.rb
- class CreateUsers < ActiveRecord::Migration
- def self.up
- create_table :users do |t|
- t.string :username
- t.string :password
- t.timestamps
- end
- end
- def self.down
- drop_table :users
- end
- end
- $ rails generate migration prepopulate_users
- invoke active_record
- create db/migrate/20111004024648_prepopulate_users.rb
- $ cat db/migrate/20111004024648_prepopulate_users.rb
- class PrepopulateUsers < ActiveRecord::Migration
- def self.up
- # Assuming the 'results' is set up as an Enumerable for your data
- results.each do |row|
- u = User.new( :username => row[:username],
- :password => row[:password] )
- u.save!
- end
- end
- def self.down
- end
- end
Add Comment
Please, Sign In to add comment