TL;DR, Activerecord without rails is a headache, but it’s also a good exercise if you are struggling to find the line between activerecord and rails magic.
As developers we break down problems into smaller manageable pieces and this approach works well when learning a new framework. When first confronting rails I decided to break up the problem and first learn activerecord first. The project I embarked on was to scrape down some information that would serve as the seed data for a future rails application and I decided to do this in a non rails environment using the gem Activerecord.
The first thing I did was design some barebone structure of the classes. One of the objects I wanted to store for this scrape was a product which would represent something with a name and a price.
Next I need to set up the database for ActiveRecord to use. To do this I would need a migration. So to examine a basic migration I started by making a new rails project and generating an empty migration.
This is just a ruby object that inherits from
ActiveRecord::Migration so in my project I created a new file and set up my first migration.
This simple migration just creates a new table products. The next step was to find out how to run a migration without the handy rake task. This turned out to be the hardest part of the project since information on ActiveRecord that is not tied to rails is scarce and in the end I decided to drop into irb…
Here we have a large list of method this migration object defines. Looking at this list the
migratemethod jumps out at me for a potential way to run a migration so next I tried this method.
Lets try this with an argument, how about the method it should use?
Thats promising lets look into how to make a connection to a database! After looking around google for awhile I found this code:
Just adding this at the top of the migration file, not the best solution but this is just exploring. Then running that file…
Finally playing around with the Product class either in irb or just in the file…
Thats it with the class made saving the information to the database was as simple as:
Doing this project helped me to understand the line between active record and rails. Also was really beneficial in learning MVC architecture since I just created a rails model independent of any magic!
Make yourself useful.