Seeding rails application with data

While development I like to have some sample data for testing and demo purposes. Instead filling them out using application interface, rails console or database operation rails has a slick way of seeding your database.

When you create a new rails application you can find a file called seeds.rb on db directory. This file can contain all your seeding data as follows

projects = Project.create([{:title => 'xxxxx', :description => 'yyyyyyyy'}, {:title => 'rrrrrrrrr', :description => 'zzzzzzzzzzzzz'}])

To execute this file and fill your database with seeding data run

rake db:seed

Note that if you run it more than once you’ll have your data filled twice in the database, to reset your database run

rake db:reset

Having your seeding data in ruby file can give you some advantages as you can use loops to fill data series or use other tools such as Faker. To use faker with your seed data:

1- Add gem ‘faker’ to your Gemfile

2- Add require ‘faker’ on top of seeds.rb

3- Use faker in your seed data

projects = Project.create([{:title => 'xxxxx', :description => Faker::Lorem.paragraph(10)}])

No related posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>