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 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:
It includes activerecord and pg, but also the faker gem, because it will be help you to define your examples data.
On lib/models.rb you can define the objects/records that you need. This file is already required to run your seeds and examples.
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”.
As this is “playing” code, instead of migration, you will create directly the schema on db/schema.rb.
With “ruby db/setup.rb” you will create or re-create the database, load the schema and run the seeds.
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>
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.
Here are some examples that I have shared, using this template (or previous versions of it):
Get for free the first part of the ebook Fix n+1 queries on Rails that will help you: