Mar 24, '25 02:00

In-depth study of Ruby on Rails: using Active Record to interact with databases

Ruby on Rails – a high-level framework that runs on Ruby. The effectiveness of this tool is manifested in its built-in libraries, including Active Record, which is an ORM (Object-Relational Mapping) library. Active Record and ORM have become a convenient to...

Read post
Share
🔥 More posts
This content has been automatically translated from Ukrainian.

Ruby on Rails – a high-level framework that runs on Ruby. The effectiveness of this tool is manifested in its built-in libraries, including Active Record, which is an ORM (Object-Relational Mapping) library.

Active Record and ORM have become a convenient tool for interacting with databases without writing SQL code.

Active Record: what it is and how to use it

Active Record implements the “Convention over Configuration” approach, which simplifies interaction with databases. You can create, update, read, and delete records from the database without directly writing SQL queries. Let's break down this process in more detail.

Creating records

user = User.new
user.name = "John Doe"
user.save

Or

User.create(name: "John Doe")

The above examples produce the same result: they create a new user with the name “John Doe”. An SQL query is generated to perform this action, but the programmer does not need to know this (actually, they should).

Updating records

user = User.find_by(name: "John Doe")
user.name = "Jane Doe"
user.save

Or

User.update(name: "Jane Doe")

Both examples update the user's name to “Jane Doe”.

Deleting records

user = User.find_by(name: "Jane Doe")
user.destroy

Or

User.delete_all(name: "Jane Doe")

This way, the user account “Jane Doe” is deleted.

Active Record Security

An important aspect of using Active Record is applying security principles. It is essential to be aware of the possibility of SQL injections and know how to prevent them. You cannot insert data provided by the user directly into the query.

User.where("name = ?", params[:name])

In this example, the value entered by the user is not used directly to create the SQL query.

By adhering to these principles, you can configure Active Record to optimally serve as a bridge between your Ruby code and the database.

🔥 More posts

All posts