Seeding the development database using the Faker gem

Updated: 

How to use the Faker gem in Rails to generate fake user and product data for development.

This lesson is from Full Stack Rails Mastery.

So far, we've manually added a couple of products as we built out the basic features of creating and editing products.
Now as we move towards adding features like a shopping cart for buying multiple products, we'll need lots more products in our marketplace. Having more data will also make it look better and feel more like a real life application.
So let's add seed the development database using the Rails db seed feature.
We can modify the seeds.rb file to add some code to generate products:
#db/seeds.rb

seller = User.create(email: "[email protected]", password: "password")

#Create products for the first seller account.
products = seller.products.create(
  [
    {
        title: "Email Newsletter Template",
        description: "<p>This <strong>email newsletter template</strong> is perfect for reaching your audience. Customize it with your branding and content to keep your subscribers engaged. With a modern design and responsive layout, it looks great on any device. Easily integrate your social media links and call-to-action buttons to drive more traffic to your website.</p>",
        price: 29
    },
    {
        title: "Ebook Template",
        description: "<p>Our <em>ebook template</em> offers a sleek and professional design to showcase your content. It's fully editable and compatible with various software, making it easy to adapt to your needs. The template includes multiple page layouts, customizable graphics, and a stylish cover page. Perfect for authors, marketers, and businesses looking to publish high-quality ebooks.</p>",
        price: 49
    },
    {
        title: "CV Resume Template",
        description: "<p>Stand out in your job search with this <strong>CV resume template</strong>. Designed to highlight your skills and experience effectively, this template features a clean and modern layout. It includes sections for your professional summary, work history, education, skills, and more. Easy to edit in popular software programs, this template helps you make a great first impression.</p>",
        price: 19
    },
    {
        title: "Flyer Template",
        description: "<p>Create stunning flyers with our <em>flyer template</em>. Ideal for promoting events, sales, or special announcements, this template is highly customizable. Choose from a variety of color schemes, fonts, and graphics to match your brand. Print-ready and easy to edit, this flyer template ensures your message stands out and grabs attention.</p>",
        price: 15
    },
    {
        title: "Presentation Template",
        description: "<p>This <strong>presentation template</strong> will help you deliver powerful presentations with ease. Professionally designed slides are ready to use and include various layout options for text, images, charts, and graphs. Enhance your presentations with visually appealing graphics and ensure your key points are communicated effectively. Perfect for business meetings, conferences, and educational purposes.</p>",
        price: 35
    }
  ]
)

#Attach product images from a local folder.
products.each do |product|
  Dir.children("db/images/#{product.title}").each do |filename|
    filename = Rails.root.join("db/images/#{product.title}/#{filename}")
    puts filename
    product.images.attach(io: File.open(filename), filename: filename)
  end
end

There are two steps here - first we're creating a few products with title, description and price for one seller. I'm using a single seller right now so that we don't have to switch the session if we want to edit a product.
Feel free to add more seller accounts and their corresponding products.
After creating the products, we're also attaching images to each of them.
You can download the images used here from this link. Unzip the file and store the files under db/images inside your Rails app folder.
If you don't want to hardcode product data, you can use the Faker gem to create fake user and product data on the fly.
Start by adding the gem to the Gemfile. You wouldn't use this in production, so limit it to the development and test environments like this:
#Gemfile
group :development, :test do
  gem 'faker'
end

Then install it:
bundle install

Now, you can use it in the seeds file like this:
#db/seeds.rb

#We'll need this library to fetch images from the internet
require 'open-uri'

#Add missing name and profile photos for existing users.
User.find_each do |user|
  user.update(name: Faker::Name.name) if user.name.nil?
  if !user.profile_photo.attached?
    profile_photo = URI.open("https://robohash.org/#{user.name.gsub(' ', '')}")
    user.profile_photo.attach(io: profile_photo,
                            filename: "#{user.name}.jpg")
  end
end

#Create a new seller account with a profile photo
seller = User.create(
          name: Faker::Name.name,
          email: Faker::Internet.email,
          password: "password")

profile_photo = URI.open("https://robohash.org/#{seller.name.gsub(' ', '')}")
seller.profile_photo.attach(io: profile_photo,
                            filename: "#{seller.name}.jpg")

#Create new products for the seller
products = seller.products.create(
  6.times.map do
    {
      title: [Faker::Commerce.product_name, ["Template", "Wallpaper", "Kit"].sample].join(" "),
      description: Faker::Lorem.paragraphs(number: 4).join("<br/><br/>"),
      price: Faker::Commerce.price
    }
  end
)

#Attach product images from a Faker URL.
products.each do |product|
  3.times do
    #This points to "https://loremflickr.com/300/300" which returns a random image
    image = URI.open(Faker::LoremFlickr.image)
    product.images.attach(io: image, filename: "#{product.title}_#{i}.jpg")
  end
end

Faker has lots of built-in generators for different types of data. 

We're using Faker and RoboHash to generate user name, email, product names, descriptions and price. 

Then run the seed command:
bin/rails db:seed

If you want to delete all existing records and seed the database from scratch, you can run:
bin/rails db:seed:replant