Active Record in Rails

Tram Ho

When exposed to any new language, basically all of us are the same at first, with the eyes of the A, the mouth of the O … in short, there is a strange look. As time goes on with actual learning and practice, each person will develop certain skills and knowledge of that language. From eye to eye, familiar to hand to master and understand. I came to Ruby by chance and was very surprised when participating in a workshop program called Rails Girl – a program for girls who are passionate about programming or who do not have a special affection to purpose of rekindling and spreading that passionate fire.

From the beginning, when exposed and introduced to a relatively new language in Vietnam, I was really surprised at the speed of creating a very simple Ruby website in just a few notes. Feel excited to explore, discover and discover this surprising language. However, just learning to do it quickly without really understanding it is not a good or long-term way to work with any language. Prerequisite is still your thinking and at the same time you spend time to learn, learn and practice. From recognizing your own limitations on the knowledge of the language you are working with every day, you still don’t really understand it. In this series of articles, I take the time to translate and revisit knowledge from basic to advanced to reinforce my knowledge and learn about the smallest niches that have been missed in the past. virginity is trainning. Or to say it beautifully, “Love again from the beginning” =))

Active Record Basics The purpose of this article, for us to understand and know more about:

What are Object Relational Mapping and Active Record in Rails, and how are they used? How to align Active Record with MVC pattern. How the Active Record model manipulates data stored in a relational database Convention on naming Active Record schema. The concepts of migration, validations, callbacks database.

1. What is Active Record?

Surely we are no strangers to the MVC pattern. In Ruby, the Actice Record is the M in the MVC pattern

which is the layer of the system responsible for representing business data and logic

In a nutshell, it is considered as the layer of the system with the function of displaying logic and business data. Facilitates the creation and use of business objects, whose data needs to be stored continuously to a DataBase. It is an implementation of the Active Record pattern which itself is a description for the Object Relational Mapping system.

1.1 The Active Record Pattern:

Active Record is described by Martin Fowler in his book Patterns of Enterprise Application Architecture. In Active Record, objects carry both data and ongoing behavior on that data. Ensuring the data access logic is part of the object supports the object user how to write and read data from the DB.

1.2. Object Relational Mapping (ORM):

ORM for short – is a technique to connect the objects of an application to the corresponding tables in a relational database management system. Using ORM, the properties and relationships of objects in an application can be easily stored and accessed from the DB without writing SQL statements directly.

1.3: Active Record is considered as an ORM framework:

Given many mechanisms and important are the following capabilities: Represent models and their data. Represent associations between these models. Represent inheritance hierarchies through related models. Validate models before they get persisted to the database. Perform database operations in an object-oriented fashion.

2. Conventions on config in Active Record

When writing applications that use other programming languages ​​or frameworks, it may be necessary to write a lot of configuration code. This is especially true for ORM frameworks in general. However, if you follow Rails’ accepted conventions, you need to write very little configuration when creating Active Record models.

2.1. Naming convention:

Active Record will use some default naming conventions, to figure out how to map models to tables created in the DB. Rails will pluralize the class name to find the corresponding table in the DB. Rails’ conversion mechanism is very powerful, capable of changing regular and irregular words into the plural (and singularize). When using class names with two or more words, the model class name must follow Ruby conventions, using the CamelCase pattern, while the table name must contain words separated by underscores.

Examples are as follows:

2.2: Schema Conventions

Active Record uses naming conventions for columns in database tables, depending on the purpose of these columns. Foreign keys – named after the form singularized_table_name_id (e.g. item_id, order_id). These are fields that Active Record will look for when you create associations between your models. Primary keys – By default, Active Record will use an integer column named id as the table’s primary key. When using Active Record Migrations to create the tables, this column will be created automatically.

In addition, there are a number of optional column names that will add additional features to Active Record instances as follows: Created_at: Automatically set to the current date and time when the record was first created. Updated_at: Automatically set to the current date and time whenever the record is updated. lock_version: Add optimistic locking to a model. type: Specifies the model using Single Table Inheritance (association_name) _type: Stores the type for polymorphic links. (table_name) _count: Used to cache the number of objects that belong to links. * For example *, we have the comments_count column in the posts table, so here in a Post class there are many instances of Comments will cache the number of comments Already available for each post.

3. Initialize Active Record Models

It’s easy for us to create AR mode (Active Record – this article covers a lot of this word, so I’ll write it down and call it AR for short).

Doing so will create a Model / Article class and it will map to the table articles in the DB. And by the way, we can also map the columns of each row in that table with the properties of the class. Suppose we create an article table with the following SQL statement:

Then we can also access the DB with the following commands such as:

4. Overriding the Naming Conventions

When you follow a different naming convention or need to use your Rails application with the legacy database, what happens? You do not need to worry, or worry about this, because you can easily override the default convention. AR inherits from ActiveRecord :: Base, defining some useful methods for you. You can use the ActiveRecord :: Base.table_name = method method to determine the name of the table that should be used.

5. CRUD: Reading and Writing Data

CRUD: stands for Create, Read, Update and Delete. AR automatically creates methods to allow an application to read and manipulate data stored in its tables.

5.1. Create

AR objects can be initialized from a hash or a block of blocks, even properties set manually after initialization. For example: We have the Article class above has 2 properties: title and content. User.create (name: “Nguyen van bay”, address: “Duc hoai duc ha noi”) calls the create method which will create and save a new record into the DB. Or, we can call the new method, but new it only creates an instance of the object, if we want to store the new record in the DB, after the new method, we can call save as follows:

5.2. Read

AR provides a rich API for accessing data in a database. Here are a few examples of the different data access methods provided by AR

Get all records of User User.all

Get the first record User.first

Count the number of records User.count

Find all users whose address is “Duc User.where(name: "Nguyen van bay").order(created_at: :desc) Ha Noi” and sort by created_at User.where(name: "Nguyen van bay").order(created_at: :desc) For more information, refer to the Active Record Query Interface.

5.3. Update Once an AR object is retrieved, its properties can be modified and saved in the DB.

5.4. Delete

A User object after being removed, we can also remove or destroy it from the DB

6. Validations

The AR allows us to validate the state of an object before writing it to the DB. There are many methods that we can use to check the object as well as validate its attribute values ​​are not empty, are unique and do not yet exist in the DB in a specific format and more. Validation is an important issue to consider when maintaining a DB. Therefore, the methods save and update at runtime: they will return false when validation fails and do not actually perform any operations on the database. In addition, they also have siblings other than the grandfather is save! and update !. With us, validations always run. They raise raise ActiveRecord :: RecordInvalid if validate fails.

7. Callbacks

Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

It is understandable that Callbacks record activity that allows attaching code for certain events in the model life cycle. This allows you to add behavior to the model to execute code when events occur. For example, when creating a new record, update or delete that record … You can read more about Callback here Active Record Callbacks

8. Migrations

Rails provides a domain-specific language for managing database schemas called migrations.

9. References

https://guides.rubyonrails.org/active_record_basics.html

Share the news now

Source : Viblo