Ruby on Rails ActiveRecord
Overview
Data in an object-oriented program is frequently arranged into hierarchies of classes, whereas data in a database is structured into tables. Since the application may have to work with the database to store, retrieve , or edit data, this could lead to a difference between the two views. Developers could have to manually map between the two views using complicated low-level code without a method to change these views, which can be time-consuming and error-prone. The use of Object Relational Mapping(ORM) becomes necessary.
What is an Active Record?
The Active Record pattern is a technique utilized in software development that eases the process of communicating with databases. It is a method that permits developers to connect database tables to Ruby classes and vice versa.
Active Record is a Ruby gem that provides a version of the Active Record pattern. In the Model-View-Controller (MVC) pattern, Active Record is classified as the M (Model) component. The Model constitutes the data and business logic of the application, and its function is to engage with the database.
-
Active Record Pattern The Active Record pattern is a variation on the Model-View-Controller (MVC) architectural pattern, which separates data, presentation, and business logic in an application. We can use Active Record to define database tables as classes in an object-oriented programming language, thus making it easier to interact with and modify data in a database.
-
Object Relational Mapping: Object-relational mapping(ORM) is a programming technique that helps map database tables to object-oriented classes in our application. It establishes a correlation between database tables and classes, database table rows and objects, and database table columns and object attributes. Active Record automates the mapping procedure, eliminating the need for developers to interact with database constructs such as tables, rows, or columns. Instead, the application interacts only with classes, attributes, and objects.
-
ORM Framework: It provides a set of tools and utilities to simplify database interactions and is frequently used in conjunction with Active Record. Developers can write database queries in favorable programming languages rather than SQL, all because of ORM frameworks. The pattern is used in many popular web frameworks, including Ruby on Rails, Laravel, and Django.
-
Naming Conventions: Naming conventions are an essential part of Active Record, as they help to ensure consistency and maintainability in an application. In Active Record, class and attribute names are typically derived from database tables and columns. For example, if a database table is named "users" the corresponding Active Record class would be named "User". Similarly, if a database column is "email_address," the corresponding attribute in the class would be "email_address."
Suppose we have two models - User and Post. A User can have many Post models, and a Post model belongs to a User. The corresponding database tables will be users and posts, respectively.
The User model class will have an association named posts, and the Post model class will have a foreign key named user_id. The code for the models will look like this:
How to Create Rails, Active Record Models
To generate Rails Active Record Model:
-
Run the following command in the root directory of our Rails application:
By convention, ModelName should be in CamelCase. For example,
-
In the directory app/models, user.rb will be created as a model. We should add validations(like validates), and relationships(like has_many) in our model to ensure consistency, accuracy, and reliability of the data being stored and manipulated by the application. For example, the User model may add the following code:
Email, password, and posts are three of the User model's properties that are included in this code. Also, there are two validations: a legitimate and distinct email address and a password that is at least eight characters long. It contains a link between the User model and the Post model, showing that a user may have multiple posts.
-
After defining our model, run the following command in the terminal:
The appropriate database tables and fields for our model are created by this command. We have successfully built an Active Record model for Rails. Now that we have this model, we can use it to interact with our database in a variety of ways, including querying and making associations as well as adding, updating, and removing records.
CRUD operations in Active Record
The process of manipulating data is often referred to as CRUD, which stands for Create, Read, Update, and Delete. Active Record offers various techniques to carry out these CRUD operations on database records. Below are the most commonly used methods:
Create: To insert a new record into the database, we can use the create method. For example:
Read: To retrieve one or more records from the database, we can use the find, find_by, or where methods. For example:
Update: To modify an existing record in the database, we can use the update method. For example:
Delete: To remove a record from the database, we can use the destroy method. For example:
These methods can also be coupled to carry out more complicated tasks like updating multiple records simultaneously or removing all records that meet specific criteria.
Callbacks and Validations
Callbacks: Callbacks are methods that get executed at specific moments during the lifecycle of a record in Active Record. For example, we can use before_save callback to alter data before it gets saved to the database or the after_create callback to execute additional actions once a new record is created. By callbacks, we can automate various tasks and ensure that data remains consistent throughout the application.
Validations: Active Record includes built-in validation methods that allow us to define rules for data to ensure it meets specific requirements. For instance, the validates_presence_of validation can be used to ensure that a required field is not left blank, while the validates_uniqueness_of validation can be used to guarantee that a field is unique. Using validations, we can avoid saving invalid data to the database and provide users with feedback if data fails to meet the required criteria.
The following example shows the implementation of Callbacks and Validation:
The User model has two validations: validates_presence_of to ensure that name and email are present and validates_uniqueness_of to ensure that email is unique. There is a before_save callback called normalize_email which downcases the email field before saving it to the database.
FAQ
Q . How does rails Active Record follow 'convention over configuration'?
A . Active Record follows this principle by defining a set of conventions for database tables and columns, and for naming models and their attributes. For example, if you have a table named "users" Active Record will automatically create a corresponding model named "User" and assume that the table has columns named "id," "created_at" and "updated_at."
Q . What is a migration in Active Record?
A . A migration in Active Record is a way to modify the database schema over time using Ruby code instead of writing SQL statements. Migrations allow you to add, remove, or modify database tables, columns, and indexes, among other things.
Q . What is the difference between belongs_to and has_many in Active Record?
A . belongs_to and has_many are two types of associations in Active Record. belongs_to represents a one-to-one or many-to-one relationship between two database tables, where the foreign key is located in the table that belongs_to the other. has_many represents a one-to-many or many-to-many relationship between two tables, where the foreign key is located in the table that has_many the other.
Conclusion
- Rails Active Record works on convention over configuration technique, so if we follow conventions it will do our tedious task of maintaining our data in the Model class easily.
- Object-relational mapping(ORM) is a programming technique that helps map database tables to object-oriented classes in our application.
- Active Record offers various techniques to carry out these CRUD operations on database records.
- Callbacks are methods that get executed at specific moments during the lifecycle of a record in Active Record.
- Active Record includes built-in validation methods that allow us to define rules for data to ensure it meets specific requirements.