Table of contents
1.
Introduction
2.
Active Records
2.1.
Active Record Basics
3.
Class and Database
4.
Translating a Domain Model into SQL
5.
Creating Active Record Files (Models)
6.
How to Create Associations between Models
7.
Implementing Validations on Models
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Active Records

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A hierarchy of classes is used to represent data structures. The majority of data is kept in relational database tables. The object view in your software and the relational data view in the database are fundamentally different. The usage of object-relational-mapping (ORM) tools was one technique to remedy this mismatch. ORM refers to the mapping of relational database tables to object-oriented classes.

The specifics of a database's relational data are hidden beneath the object hierarchy in a flawless ORM. Active Record, one of the most significant components of the Rails library, implements ORM in Rails. Let's take a closer look into Active Record.

Active Records

Martin Fowler came up with the Active Record design pattern. The Active Record earned its name solely from this design pattern. Even with fewer lines, its code performs admirably. It's quite simple to use. If you use suitable naming strategies in your database and classes, your Active Record Rails application will not require any settings.

Another Active Record feature that makes your job easier is the implementation of a domain-specific language (DSL). A domain-specific language (DSL) is a computer language designed for usage in a certain problem domain. It lets you use dynamically produced methods, such as found by the first name, to obtain a record.

The standard ORM model, which Active Records closely follows, is as follows:

  • tables map to classes,
  • rows map to objects, and
  • columns map to object attributes.

Active Records in Rails provide a connection and interface between relational database tables and Ruby computer code that manipulates database records. The names of Ruby methods are derived automatically from the field names of database tables.

For database access, each Active Record object has CRUD (Create, Read, Update, and Delete) methods. Simple designs and straightforward mappings between database tables and application objects are possible with this method.

Active Record Basics

Classes, objects, and naming standards are some of the fundamentals of Active Record.

  • Active Record Classes and Objects:
    A class that extends the Active Record base class is used to represent each table in a database. Model objects inherit a lot of functionality via extending Active Record base classes.
    You don't need to set up any database connections while utilizing Active Records. It is in charge of an application's database connections. For each of the database columns it adds characteristics to your class.
  • Active Record naming conventions
    The CoC (convention over configuration) idea is used by Active Record. You may use many dynamic features of Active Record without any configuration if you stick to the naming standard.

Class and Database

Your model classes' database tables should be called in the plural form and in lowercase. For example, if the name of a model class is Student, the table name will be Students. Rails will find the relevant table to your model class without any configuration code if you follow this standard. It even recognizes plural nouns as plurals of singular nouns, such as 'people' as the plural of 'person.'

Rails has a feature that allows you to add plurals to a model. Using Inflector, add code to config/environment.rb to specify your own pluralization.

In case you don't want to name your database in the plural form, you may configure Rails to use singular-named database tables by adding the following line to

config/environment.rb file:

ActiveRecord::Base.pluralize_table_names = false  

Translating a Domain Model into SQL

It's often straightforward to convert a domain model to SQL, as long as you remember to write Rails-friendly SQL. In practice, you must adhere to certain guidelines.

  • Each entity (such as a book) is given its own database table, but in the plural (books).
  • A field named id exists in each entity-matching table, and it holds a unique integer for each entry placed into the table.
  • If entity y belongs to entity x and table y contains a field called x_id, then table y will have a field called x_id.
  • The values for that entity's simple properties (anything that's a number or a text) are stored in the majority of fields in any table.

Creating Active Record Files (Models)

Use the following command from the top level of the application directory to generate the Active Record files for our entities for library application:

library\> rails script/generate model Book
library\> rails script/generate model Subject

 

The auto code generated by above rails generate model book commands is as follows:

invoke        active_record
create        db/migrate/20115501100134_create_books.rb
create        app/models/book.rb
invoke        test_unit
create        test/models/book_test.rb
create        test/fixtures/books.yml

 

You're instructing the generator to construct models for books and subjects called Book and Subject. You'll see that you've capitalized Book and Subject, and singular form is used. This is a Rails paradigm that you should adhere to when creating a model.

While using the generate tool, Rails creates the actual model file, which contains all of the model's unique methods and the business rules you define, as well as a unit test file for test-driven development, a sample data file (called fixtures) to use with the unit tests, and a Rails migration, which makes creating database tables and columns simple.

Apart from many other files and directories, this will produce files named book.rb and subject.rb in the app/models directory, each with a skeleton definition.

Content available in the book.rb:

class Book < ActiveRecord::Base
end

 

Content available in subject.rb:

class Subject < ActiveRecord::Base
end

How to Create Associations between Models

You must connect your models in your Rails application if you have more than one. This can be accomplished through associations. There are three types of associations supported by Active Record:

  • one-to-one: When one object has exactly one of another, it is said to be a one-to-one relationship. A human, for instance, has exactly one birthday, and a dog has precisely one owner.
  • one-to-many: When a single object can be a member of many other objects, this is known as a one-to-many relationship. One subject, for example, may have a large number of books.
  • many-to-many: When the first object is related to one or more of the second object, and the second object is related to one or many of the first object, a many-to-many relationship exists.

These connections are indicated by declaring has one, has many, belongs to, and has and belongs to many in your models.

Now you must tell Rails what kinds of associations you wish to create in the library data system. To accomplish so, make the following changes to book.rb and subject.rb:

class Book < ActiveRecord::Base
   belongs_to :subject
end

 

We selected a single subject in the preceding example because a single Book might belong to a single subject.

class Subject < ActiveRecord::Base
   has_many :books
end

 

We've used plural books because one subject can have numerous books here.

Implementing Validations on Models

The validations are implemented using a Rails model. Because the data you're entering into the database is described in the Rails model, it's only natural to specify what constitutes valid data in the same place.

The validations are as follows:

  • The value of the title field should not be NULL.
  • The value of the price field should be numeric.

Open book.rb in the app\model subdirectory and put the following validations:

class Book < ActiveRecord::Base
   belongs_to :subject
   validates_presence_of :title
   validates_numericality_of :price, :message=>"Error Message"
end

 

  • validates_presence_of"NOT NULL" fields are protected from missing user input.
  • validates_numericality_ofThis validation stops the user from inputting non-numerical data.

FAQs

  1. What does ActiveRecord do in Rails?
    Active Records in Rails provide a connection and interface between relational database tables and Ruby computer code that manipulates database records. The names of Ruby methods are derived automatically from the field names of database tables.
     
  2. Is ActiveRecord an ORM?
    Object Relational Mapping (ORM) is a database management technique that involves "mapping" database tables to classes and instances of classes to rows in the tables. ORMs such as Active Record are just one example; others include Sequel. DataMapper.
     
  3. What is the active record pattern in Rails?
    The active record pattern is a method of retrieving information from a database. A class encapsulates a database table or view. As a result, each object instance is associated with a single table row. When an item is created, a new row is added to the table when it is saved.

Key Takeaways

In this blog, we learned about Active Records in Rails, its basics, how to create one, translation of Domain Model into SQL, and Association between Models.

To learn more, please head to Coding Ninjas Blogs, where we bring to you exciting technical blogs.

Happy Learning!

Live masterclass