This is going to be a very straightforward article, no jokes included.

When you want to populate you database during development, you need to use a file that already comes in Rails: the seeds.rb file. You can find it inside the db folder, the same where you can find the migration and schema files.

Aside from that you’ll need two gems: the Populator gem, and the Faker gem. The last one is not actually necessary, but makes your life a lot easier, and your dummy data much more realistic.

The Populator gem will allow you to do something close to what Factory_bot does in test environment: you’ll set the data that will be provided, and the gem will automatically create several instances of your model to populate. If you only use Populator, you’ll have to hardcode the content provided - not cool.

That’s where Faker comes in. It has a huge array of fake content that is available to you. It can generate names, emails, credit card numbers, addresses, you name it. It randomly returns one every time it is called.

So, to the steps.

1 - Set your gems.

Go to your Gemfile, and make it like this:

group :development, :test do
  gem 'faker'
  gem 'populator'
end

Run in your terminal:

bundle install

Go to your _lib _folder. You’ll have to do some patching in Populator gem if you use Rails version after 5.1. Inside the lib folder, create a file called populator_fix.rb. Copy the following code and paste inside it:

module Populator
  ## Builds multiple Populator::Record instances and saves them to the database
  class Factory
    def rows_sql_arr
      @records.map do |record|
        quoted_attributes = record.attribute_values.map { |v| @model_class.connection.quote(v) }
        "(#{quoted_attributes.join(', ')})"
      end
    end
  end
end

Save it.

Go to your seeds.rb file, and require this patch. On the first line, add the following:

require_relative '../lib/populator_fix.rb'

That’s it. Your gems are set, let’s do some code!

#ruby-on-rails #rails #ruby #gem #database #development #automation #full-stack-development

How To Populate Your Database with Fake Data: Ruby On Rails Tutorial
6.15 GEEK