I've got a rails application where users have to log in. Therefore in order for the application to be usable, there must be one initial user in the system for the first person to log in with (they can then create subsequent users). Up to now I've used a migration to add a special user to the database.
After asking this question, it seems that I should be using db:schema:load, rather than running the migrations, to set up fresh databases on new development machines. Unfortunately, this doesn't seem to include the migrations which insert data, only those which set up tables, keys etc.
My question is, what's the best way to handle this situation:
Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
There should be a database file with sqlite extension on db directory of the app. On DB Browser, select Open Database option and choose that file and you should be able to view the data. Show activity on this post. Restart your server.
No, you don't need to use a db if you don't need it. However, keep in mind that Rails is vert tied with the idea of database and ActiveRecord. to require only the frameworks you need.
Try a rake task. For example:
namespace :bootstrap do desc "Add the default user" task :default_user => :environment do User.create( :name => 'default', :password => 'password' ) end desc "Create the default comment" task :default_comment => :environment do Comment.create( :title => 'Title', :body => 'First post!' ) end desc "Run all bootstrapping tasks" task :all => [:default_user, :default_comment] end
Use db/seed.rb
found in every Rails application.
While some answers given above from 2008 can work well, they are pretty outdated and they are not really Rails convention anymore.
Populating initial data into database should be done with db/seed.rb
file.
It's just works like a Ruby file.
In order to create and save an object, you can do something like :
User.create(:username => "moot", :description => "king of /b/")
Once you have this file ready, you can do following
rake db:migrate
rake db:seed
Or in one step
rake db:setup
Your database should be populated with whichever objects you wanted to create in seed.rb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With