4

I have a few tables that I would like to add about 10 rows of data to, in a manner that respects and illustrates their relationships.

  • How can I add seed data (dummy data) to my applications' development database for testing?
    I'm hoping someone could point me to a rails friendly method for doing this.

  • Is there an easy way to make the CRUD methods in each table perspective controllers?

Scott Solmer
  • 3,871
  • 6
  • 44
  • 72
E.E.33
  • 2,013
  • 3
  • 22
  • 34
  • I don't understand your second question. Can you elaborate? – Gazler Oct 12 '11 at 18:51
  • I think i just found the answer to the second question. I believe that scaffolding can help me set up my CRUD controllers and my views? – E.E.33 Oct 12 '11 at 19:24
  • 1
    Oh, yeah, a scaffold will create the CRUD functionality for you. I would recommend it for learning, not when you are actually building applications. – Gazler Oct 12 '11 at 19:25

1 Answers1

12

This is what the db/seeds.rb file is for.

You can execute it with rake db:seed

The default contents of seeds.rb

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
#   Mayor.create(:name => 'Daley', :city => cities.first)

You can use ruby in this, so to insert 10 users:

1.upto(10) do |i|
   User.create(:name => "User #{i}")
end
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • so, i need to insert code into the seed.rb file then perform a rake? I was hoping for a more automated way to add dozens of rows of data – E.E.33 Oct 12 '11 at 19:25
  • 1
    You can use loops as this is a ruby file. You can also use the faker gem https://github.com/btelles/faker if you want to use real names, etc. – Gazler Oct 12 '11 at 19:26
  • 2
    I wouldn't recommend this approach, as this is **not** what the seeds file/task is for. See [this question](http://stackoverflow.com/questions/17580031/rails-recommended-way-to-add-sample-data) for (IMO) a better answer. – Armando Fox Jun 02 '15 at 03:07
  • Is the seed.db used only for production data and rake db:fixtures:load for development and testing?? – Taysky Jun 05 '15 at 20:08
  • @Taysky is correct. Seed is for genuine seed data that your app may have. For example, a static list of planet names or roles. I would suggest creating a custom rake task under the db namespace. Use ActiveRecord to create many records via loops. – karns Sep 18 '20 at 17:21