loading...

Day 43 : #100DaysofCode - The Amazing Faker Gem

sincerelybrittany profile image Brittany ・2 min read

If you are relatively new to code and learning all about Ruby and Ruby on Rails, then you most likely have experience or heard of the seed.rb file. The file allows us to create objects/ data and add it to our database. In general, you would run rails db:seed or rake db:seed AFTER running your migration. Today, I wanted to add information to my seeds file so that I could manipulate and interact with the data in my console to confirm that everything was working properly.

My schema was simple, it looked like this:

 create_table "patients", force: :cascade do |t|
    t.string   "name"
    t.integer  "age"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

In order to generate information in my database, I was going into my console or manually creating the information by manually creating objects and filling them in like so:

homer = Patient.create({name: "Homer Simpson", age: 38})
bart = Patient.create({name: "Bart Simpson", age: 10})
marge = Patient.create({name: "Marge Simpson", age: 36})

But then I was introduced to the Faker Gem that changed my life. First, I added the faker gem to my Gemfile gem 'faker' then I added this simple iteration to my seeds.rb file:

5.times do |t|
    name = Faker::Name.name 
    age = Faker::Number.between(from: 15, to: 90 ) 
    Patient.create(name: name, age: age)
end

Lastly, I ran rails db:seed and TADA, my database was filled with five patients. The Faker Gem has tons of information available for times when you need to generate information quickly for your database. I recommend checking out the documentation and adding it when necessary to save you the time.

I hope this helps another code newbie like myself.

Thanks for reading!

Sincerely,
Brittany

Posted on by:

sincerelybrittany profile

Brittany

@sincerelybrittany

Developer | Software Engineer 👩🏾‍💻 | Determined | Music & Dance | Completed #100DaysofCode | #WomenWhoCode

Discussion

markdown guide