Benito Serna Tips and tools for Ruby on Rails developers

Active record playground, for rails developers that want an easy way to practice with active record in isolation

March 29, 2022

I want to share with you my “Active record playground template”.

It is a template that you could use as a guide or by cloning the repo and following the instructions in the README if you want to play with some Active Record models in isolation and without creating a full rails app.

I was repeating my self over and over

I was setting up the structure of this template from scratch over and over again until I decided to do it in a little more general way.

Now it is much more faster and easier for me to start playing with Active Record in isolation. And now, I hope it also can help you.

The default structure of this template will make some decision for you:

1. The starting Gemfile

It includes activerecord and pg, but also the faker gem, because it will be help you to define your examples data.

2. A place for your models

On lib/models.rb you can define the objects/records that you need. This file is already required to run your seeds and examples.

3. A place for your seeds

On db/seed.rb you will be able to define your seeds using the objects defined on lib/models.rb. You will also be able to run them with “ruby db/seed.rb”.

4. A place for the schema

As this is “playing” code, instead of migration, you will create directly the schema on db/schema.rb.

5. The db setup command

With “ruby db/setup.rb” you will create or re-create the database, load the schema and run the seeds.

6. A place to define your examples

You will have an /examples dir, to add the examples files that you need.

Requiring examples/config will require the database initialization code and the models defined on lib/models.rb

You can run the examples with ruby examples/<file name>

ruby example/00_example.rb

Use the template

Use this template if you want to play with Active Record in isolation without creating a full rails app.

You can find the template on https://github.com/bhserna/active_record_playground

You can use it as a guide or by cloning the repo and following the instructions on the README.

Some examples of using this template

Here are some examples that I have shared, using this template (or previous versions of it):

Related articles

Download a free ebook to learn the basics of n+1 queries on Rails basics

Learn just enough fundamentals to be fluent preloading associations with ActiveRecord, and start helping your team to avoid n+1 queries on production.