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
1 2 | SELECT * FROM Customers; |
and convert these results into an array. When using Active Record, we can write
1 2 | Customer.all |
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.
1 2 3 4 5 6 | // Hai bước để tạo mới một User new_user = User.new(name: "huythanh") new_user.save // Tạo một User với một bước new_user = User.create(name: "huythanh") |
We can update the object by taking it from the database and modifying its properties and saving it back to the database.
1 2 3 4 5 6 7 8 9 | // Các bước để lấy dữ liệu ra, thay đổi và lưu lại user = User.find_by(name:"huythanh") user.name = "dohuythanh" user.save //Hoặc chúng ta có thể dùng hàm update để rút gon code user = User.find_by(name:"huythanh") user.update(name:"dohuythanh") |
Deleting a row from the database can be done using the destroy
method
1 2 3 | user = User.find_by(name:"huythanh") user.destroy |
References
- Read more about Active records here