Creating Database Records With Active Record Methods

Carl-Brain Egebe
3 min readAug 9, 2021

Active Record is a ruby gem which uses class instances(objects) to create records in databases. Active Record is also capable of interacting with the database to get certain bits of information as well as persist data.

Active Record has methods in place for such interactions. Here, I’ll be demonstrating how a couple of them work. Those methods being: .new, .create_with, and .find_or_create_by.

Using .new creates a new record. Upon creation, all the attributes of that record are set to “nil”.

Attributes can then be set like this:

After doing all this, a record is created but it is not part of the database just yet. In order to make it part
of the database, the .save method will have to be called on it: mike.save

The create_with method combines those the previous two steps. The create_with method takes in key value pairs as an argument
Those key value pairs could be comma separated or inputted as a single hash.

Lets assume you are storing grocery items into a database table. Every time you think of something that should go on the grocery list, you create a record in the database for that item. Now, lets say you just took the last cookie from the cookie jar and want to add cookies to your grocery list. However, you may or may not have already put cookies on your shopping list earlier.
You need a way to make sure there is a single record for cookies in your table of grocery items. That’s where the find_or_create_by method comes in. Here’s how it works:

If there is an existing record with a name attribute of “cookies”, that record will be returned. However, if there is no such preexisting record, a record would be created with the attributes specified in the parentheses. Either way, a record gets returned, indicating it is in the database table.

--

--