The ultimate guide to understanding ActiveRecord
In my last post, I wrote out a guide to writing out object relationships in Ruby. I think it is so important to understand what is going on under the hood of ORMs (object relational mappers) before starting to implement. By understanding these key concepts, it becomes an innate tool in understanding data structures and how to tackle a problem from the beginning. This will save you a lot of headache while building your applications.
In this post, I want to delve deeper into this topic by writing out a guide to ActiveRecord. ActiveRecord is an ORM designed for Ruby that “facilitates the creation and use of objects whose data requires persistent storage to a database.” It’s a commonly used system in building web applications in Ruby, and a system one must be competent in when moving on to learning and truly understanding Rails.
Let’s talk overview for a second. ActiveRecord is the Model in an MVC, or Model-View-Controller. MVC is a software design pattern used for creating user interfaces by dividing the program logic into at least 3 interconnected elements (sound familiar? OOP!) ActiveRecord works as the model by maintaining the relationships between the objects in our applications and the database. (In a later post, I’ll dive deeper into the View and Controller of an MVC).
As an ORM, ActiveRecord connects the objects of an application to tables in a relational database management system. With an ORM, storing and retrieving properties and relationships of objects in an application are made easy without the need to directly write SQL statements. (If you don’t understand SQL yet, I highly suggest getting comfortable at least understanding what a query language does. It helps to be able to fully understand ActiveRecord).
What does ActiveRecord do though?
Great question, I’m glad you (well, I really) asked! ActiveRecord does a lot, but the most important things is its ability to represent objects/models and their data, represent the associations between these objects/models, represent inheritance hierarchies through related models, validate models before persisting to the database, and perform database operations in an object-oriented fashion.
Let’s talk convention
When writing applications in ORM frameworks, it is usually necessary to write a lot of configuration code (ie, my last post on object relations). By following the conventions adopted by Rails, ActiveRecord will write most of these for you. Conventions are the default way in which code is written so as not to cause much confusion. We’re going to dive into this a bit:
To find out how to map between models and database tables, ActiveRecord uses naming conventions. Here’s the gist:
- model classes are singular and in CamelCase
- database tables (created with migrations) are plural and in snake_case
Naming the columns in the database tables also follows a few conventions:
- foreign keys are singular and snake_case
- primary keys are by default called ‘id’ (these are automatically created when using migrations)
- column names are lowercase and in snake_case
Setting Up ActiveRecord
- Include the
activerecord gemin your Gemfile or run
gem install activerecordin your terminal (Documentation on activerecord gem)
- In your
config/environment.rbfile, establish the connection to ActiveRecrod. This is how to tell ActiveRecord where the database is located. I am versed in using sqlite3 as my SQL, so below is an example of how I would set this up. Once this is run, ActiveRecord::Base will store the database table as a class variable at
Creating ActiveRecord Models
There’s really only one extra step here from your ordinary class creation:
- Subclass your model to ActiveRecord::Base class
Creating ActiveRecord Tables
I’ve touched on migrations earlier, which if that sounds foreign, it is a function of the task runner
Rake (Rails can also perform migrations, but we’ll cover that in a later post)! Here I have linked a simple guide to understanding Rake. I am going to assume you already have rake installed in your application and understand the basic commands.
- In your terminal, create a migration with the proper conventions to create a table for each class.
rake db:create_migration NAME=create_boats
This will create a migration file that will create a class
CreateBoats , which you can
CREATE TABLE for each model. Here’s an example:
*Side note: Make sure you’ve done the proper mapping of object relations before starting to create your table. You should know exactly what columns you need for each models’ database table before creating them.
2. In your terminal, run
rake db:migrate to create the table.
*Check that the table has been created by running
rake db:migrate:status . If you see “up” next to your table, you’re good to go. If you see “down”, that means it hasn’t been created.
Reading and Writing Data with CRUD
One of the great things (probably the greatest) about ActiveRecord is it’s ability to perform database operations in object-oriented fashion. CRUD is an acronym for the verbs used to operate on data: Create, Read, Update, and Delete. Let’s look at these a bit closer.
These methods allow users to add new records so the data can persist in the database. Models/objects can be created from a hash, block, or have the attributes manually set after creation.
.new returns a new object
.save commits the record to the database
.create returns a new object AND saves it to the database
So, you can use
.save together OR
.create does the job of both!
These methods allow users to see the data stored in the database.
.all return a collection with all objects in database
.first returns the first object in database
.find_by() takes a hash with information and finds the first object that matches (think
.where() takes a hash with information and finds all users that match (think
There are plenty more, but these are the ones I’ve used to most.
Once an object has been retrieved, these methods can change and/or update its attributes and save it to the database.
.update() takes a hash with updated information and saves the new information to the database
.update_all updates several records in bulk
These methods allow us to delete objects from the database once retrieved.
.destroy removes object from database
.destroy_all removes several records in bulk
I hope that this was helpful in understanding how using ActiveRecord can work with you in creating web applications. My main tips here are to really understand object relations and SQL. ActiveRecord is a great combination of both, so understanding them really helps you understand ActiveRecord! The rest is just putting it all together!
Active Record Basics - Ruby on Rails Guides
Active Record BasicsThis guide is an introduction to Active Record.After reading this guide, you will know: What Object…
Model-view-controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces…