Ruby on Rails: Seeding Data

  • Before we begin… (pre-intro)
  • Intro
  • Faker
  • Other ways to seed…
  • Outro

Before we begin, make sure that you have your tables (schema) set up and their associations. Click on the next two links if you need a little help with that.

https://guides.rubyonrails.org/active_record_migrations.html

https://guides.rubyonrails.org/association_basics.html

Creating a rails app/website requires a lot of coordination between a lot of models through associations. Then you have to toss in model methods, controllers, views, routes, and… well, you get the point. Any project or product is daunting to begin with.

By injecting some data into your project and making it look more like a real concept than some abstract idea (programming provides enough of that), you can find it much easier to navigate your project through the back and front end of your code.

Table looks like this:
create_table "boxes", force: :cascade do |t|
    t.string   "brand"
    t.string   "sender"
    t.string   "receiver"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

Faker is one of the more popular methods of seeding data into your project without the headache of thinking up relevant words. After installing your Faker gem, simply go to your seed.rb file in the db folder of your rails project and type in some code similar to this…

25.times {
   Box.create(
   brand: Faker::Company.name,
   sender: Faker::Name.first_name,
   receiver: Faker::Name.first_name
   )
}

aaaand type in ‘Rake db:seed’ into your consoler and let the magic happen. If you need more data user 50.times or 100.times, as long as your environment can handle it all at once. Or use less…

Perhaps Faker isn’t for you, maybe you want some data that is more specific to your needs! .each is your friend. The hard of writing Box.create fifty times is subverted by creating an array of data and then filtering through that list with .each. Here is an example…

box_list = [
    ["Company 1", "John", "Jane"],
    ["Company 2", "Alex", "Alexa"],
    ["Company 3", "Samantha", "Sam"],
    ["Company 4", "Martha", "Mark"]
]

box_list.each do |obj|
    Box.create(company: obj[0], sender: ob[1], receiver: [2])
end

This does require some more work than using the Faker gem, but using relevant data can be helpful depending on your programming preferences. But using either of these two methods is much better than typing Box.create over and over again.

Here are some additional links and threads to further your seeding knowledge or some common errors you may get in the seeding world:

Leave a comment

Design a site like this with WordPress.com
Get started