Guest User

Untitled

a guest
Aug 21st, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. Rails: How to populate Db with data without migrations getting in the way?
  2. $ rails new example -d mysql
  3. $ cd example/
  4. $ rails generate scaffold Users username:string password:string
  5. invoke active_record
  6. create db/migrate/20111004022310_create_users.rb
  7. create app/models/user.rb
  8. ...
  9. ...
  10.  
  11. $ rake db:setup
  12. /Sites/example/db/schema.rb doesn't exist yet. Run
  13. "rake db:migrate" to create it then try again. If
  14. you do not intend to use a database, you should
  15. instead alter /Sites/example/config/application.rb
  16. to limit the frameworks that will be loaded
  17.  
  18. $ rake db:migrate
  19. == CreateUsers: migrating ====================================================
  20. -- create_table(:users)
  21. -> 0.2389s
  22. == CreateUsers: migrated (0.2390s) ===========================================
  23. $ rake db:setup
  24. -- create_table("users", {:force=>true})
  25. -> 0.1460s
  26. -- initialize_schema_migrations_table()
  27. -> 0.5908s
  28. -- assume_migrated_upto_version(20111004022310, "db/migrate")
  29. -> 0.0010s
  30.  
  31. $ rails console
  32. ruby-1.9.2-p180 :007 > u = User.new(:username => 'test', :password => 'testing?')
  33. => #<User id: nil, username: "test", password: "testing?", created_at: nil, updated_at: nil>
  34. ruby-1.9.2-p180 :008 > u.save!
  35. => true
  36. ruby-1.9.2-p180 :009 > User.all
  37. => [#<User id: 2, username: "test", password: "testing?", created_at: "2011-10-04 02:33:56", updated_at: "2011-10-04 02:33:56">]
  38.  
  39. $ cat db/migrate/20111004022310_create_users.rb
  40. class CreateUsers < ActiveRecord::Migration
  41. def self.up
  42. create_table :users do |t|
  43. t.string :username
  44. t.string :password
  45.  
  46. t.timestamps
  47. end
  48. end
  49.  
  50. def self.down
  51. drop_table :users
  52. end
  53. end
  54.  
  55. $ rails generate migration prepopulate_users
  56. invoke active_record
  57. create db/migrate/20111004024648_prepopulate_users.rb
  58. $ cat db/migrate/20111004024648_prepopulate_users.rb
  59. class PrepopulateUsers < ActiveRecord::Migration
  60. def self.up
  61. # Assuming the 'results' is set up as an Enumerable for your data
  62. results.each do |row|
  63. u = User.new( :username => row[:username],
  64. :password => row[:password] )
  65. u.save!
  66. end
  67. end
  68.  
  69. def self.down
  70. end
  71. end
Add Comment
Please, Sign In to add comment