0

Happy New Year everyone.

In my Rails 4 application I have a table plans containing the records for the plans that a user can subscribe to.

It is absolutely paramount for the app that this table is populated at any time, in development, test, and production mode. Otherwise the app will not work.

What is the best way to create those records?

Should I put a create method into an initializer? Or set up a rake task and run it manually whenever I restart the server (sounds a bit cumbersome, though)?

Thanks for any help in this matter.

Tintin81
  • 9,821
  • 20
  • 85
  • 178

1 Answers1

2

Rails has a 'seeds' feature that should be used for seeding a database with initial data. It's a really simple feature: just fill up db/seeds.rb with some Ruby code, and run rake db:seed

source: http://edgeguides.rubyonrails.org/active_record_migrations.html#migrations-and-seed-data

If you want to use data in your test environment, you might also be interested in using fixtures for your plans. Take a look at http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures

Sander Garretsen
  • 1,683
  • 10
  • 19
  • Sounds good and I've just tested it. Problem is I have to run `rake db:seed` manually every time. – Tintin81 Jan 01 '15 at 14:35
  • I'm not sure what you mean with 'every time'. Once the data is seeded, why do you want to run the seeds again? – Sander Garretsen Jan 01 '15 at 14:40
  • For example, every time I run my test suite using the `rspec` command. I wouldn't want to type `rake db:seed` every time before I run a test. – Tintin81 Jan 01 '15 at 15:17
  • 2
    You can call 'Rails.application.load_seed' inside your test. Take a look at this question: http://stackoverflow.com/questions/1574797/how-to-load-dbseed-data-into-test-database-automatically – Sander Garretsen Jan 01 '15 at 17:21
  • OK, I actually ended up creating the table in an initializer which works very well for me and feels good too. Thanks for your help. – Tintin81 Jan 01 '15 at 20:17
  • you might also be interested in using fixtures for your plans. Take a look at http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures – Sander Garretsen Jan 01 '15 at 20:43