When I first learned Rails, I heard a lot about “rails magic.” Rails builds upon the functionality of Ruby by adding multiple shortcuts across every aspect of an app. It not only makes projects faster to build, it also makes them more enjoyable since you can focus on development nuances instead of repetitive tasks. In reality, the “magic” is still the same tasks running under the hood.
When I started building more complex projects that needed to interact with a database, I started hearing about how wonderful Active Record was. To understand what the magic involved was, it’s necessary to talk about what an Object Relational Mapper (ORM) is and what problems it solves.
Google Translate for Engineers?
ORM translates the database queries to whichever backend language your website uses and vice versa.
For example, imagine your grandma is the database and she speaks Spanish (SQL) but you are at a restaurant with a menu (the backend) written in English (Ruby). You speak both languages, so you can ask your grandma what she’d like to eat and then find the corresponding item in English on the menu. In this example, you are the ORM (Active Record).
Let’s say you create a dog website called GoodBoi.com using SQL as the query language and Ruby as the backend language. We want users to be able to enter the name, gender, and breed of their dog, then have those values saved to the database. First, you would create the database structure to accept the user input with SQL.
CREATE TABLE dogs ( name string, age integer, breed string, );
Then, you would create the form in Ruby that accepts the user input.
<%= form_for @dog do |f| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.label :age %> <%= f.number_field :age, step: 1 %> <%= f.label :breed %> <%= f.select :breed %> <%= f.submit "Submit" %> <% end %>
How does the dog input go from Ruby code to being added as an additional row in the database? Active Record serves as you translator.
Hopefully, this article helped you understand the concept behind how different aspects of an app communicate with each other. Happy coding!