Active Record: The heart of Rails

Tram Ho

1. What is Active Record?

An object encapsulates a row in a database table, encapsulates database access, and adds logic to that data.

It is a simple pattern, in which a class represents a table and an object represents a row in that class.

Rails is actually made up of seven gems and Active Record is the gem that takes care of all database related tools.

2. What is ORM?

ORM stands for Object-Relative-Mapping, this is a technique that allows you to manage your database in a programming language. Active Record interacts with the database, retrieves the data and treats it like a normal Ruby object. For example, if you want to retrieve all information about Customers, you will have to write a query like

and convert these results into an array. When using Active Record, we can write

and get an array of Customer objects. Another interesting thing about Active Record is the agnostic database. Therefore, developers can focus on writing code for the application and Active Record will be responsible for connecting to the database.

CRUD with Active Record

Active Record allows you to create a Ruby object that represents a row in the database table. The new method returns a ruby ​​object that can later be saved using the save method. These two steps can be combined using the create method.

We can update the object by taking it from the database and modifying its properties and saving it back to the database.

Deleting a row from the database can be done using the destroy method

References

  • Read more about Active records here
Share the news now

Source : Viblo