THE GREAT ActiveRecord !

Chi Nguyen
3 min readJan 7, 2021

--

When getting immersed in the world of Ruby and Rails, I realized the awesomeness of ActiveRecord. Through associations between models(has_many, has_one, belongs_to), it helps us write only one line for a specific job that often needs a lot of logic in ruby and SQL. By using ActiveRecord, you can easily manipulate data stored in a relational database.

For example, we have a basic relationship between 3 models: post, blogger, and destination. Using ActiveRecord, the associations will be set like this:

ApplicationRecord is inherited from ActiveRecord::Base
The schema

Suppose you are asked to find the title of the featured post of a specific destination (the title of the destination’s post with the most likes). So what is an efficient way to find?

Obviously, we need to write a method in the Destination model.

  • A Ruby fan can write the method like this
  • A SQL fan

For the SQL query using Object-Relational-Mapper, don’t forget to add this line to your config/environment.rb file

DB = {:conn => SQLite3::Database.new(“db/development.sqlite3”)}

“development.sqlite3” is your database file located in db folder in the directory of your application. Change it to whatever your database file name.

  • ActiveRecord Magic

Because we define the associations (has_many, belongs_to) between the models, we can use ActiveRecord query to solve this problem as the easiest way.

The order method is implicit in ActiveRecord::Base. Because your model is inherited from ApplicationRecord, which is inherited from ActiveRecord::Base. So basically, your model can use the order method like above. It will order all the posts that belong to a destination by the number of likes they have. All logics include in one method. Sound like magic yet?

Maybe a harder problem can make you believe in the magic of ActiveRecord. Suppose you are asked to find a list of a blogger’s top 5 most written about destinations (the destinations with the most posts a blogger has written).

In order to solve this problem, we need to write a method in the Blogger model.

  • A Ruby fan
  • A SQL fan
  • Now ActiveRecord Magic

Actually, Ruby still uses the associations of ActiveRecord, but those mainly are Ruby logics. The nature of ActiveRecord is that binds the model in ruby application with its database. ActiveRecord helps us to write queries in a database without using raw SQL. You can see all SQL queries when you run any ActiveRecord methods in your Rails console.

Rails console

Thank you for reading. Happy Coding!

--

--