When looking to create a back-end for your web app, production structure is incredibly important for your program. Following good Model-View-Controller or MVC design patterns provides the structure to separate programming logic into three interconnected elements. Active Record takes full responsibility for the Model element, in other words, Active Record is the Model.
What is Active Record?
Active Record is an essential layer of the programming structure used to create and use objects whose data requires persistent storage in a database. This database management system is typically written out in SQL queries. With these queries, we will have to establish a connection to the database and create and run the query just to retrieve the data from the database. The beauty of Active Record is we don't have to write SQL queries to perform these tasks.
To accomplish the connection between objects from an application to the database, Active Record utilizes Object Relational Mapping also known as ORM. Active Record will then handle the process of translating data from this object to the database with SQL queries 'under the hood'.
There are some key mechanisms built into Active Record that allow for straightforward use:
- Represent models and their data.
- Represent associations between these models.
- Represent inheritance hierarchies through related models.
- Validate models before they get persisted in the database.
- Perform database operations in an object-oriented fashion.
Advantages of Convention
When creating applications it is oftentimes necessary to configure code to match our specific needs. Active Record, however, takes pride in minimal configuration by adopting the idea that most often your applications will be configured in similar ways, making a common method the default configuration.
Naming conventions:
When creating a rails application using Active Record, the same naming conventions are crucial to establish the relationship between models and the database tables. Database tables are to be plural with underscores separating each word and lowercase, using the snake_case form(book_clubs
). Model/Class will be singular with the first letter of each word capitalized(BookClub
).
Schema conventions:
Columns in database tables have their naming conventions, depending on their purpose. All columns will be singular and written out in snake case. Foreign keys should be the table's name you are trying to create an association between, followed by id (item_id
). Active Record will be looking for these columns when defining associations in your models. By default, Primary keys will be created when using Active Record Migrations to create the database tables. They will be named id
and given an integer value. There are a few reserved column names by Active Record that should be avoided, to describe the data being modeled accurately.
Creating Migrations
Rails provides a method to manage a database schema using migrations.
These migrations are stored in files created and executed using rake
. Rails will track the migration files ensuring they will be executed in sequential order and enables the rollback feature for future edits. Running rake -T
in your projects directory will prompt you will all of the available migrations Active Record provides.
An example of a possible migration file:
class CreateBooks <ActiveRecord::Migration[7.0]
def change
create_table :books do |t|
t.string :title
t.string :edition
t.text :description
t.date :publication_date
The official documentation for creating database schema can be found here Active Record Migrations.
Linking models to tables
In order to make use of Active Record's built in ORM methods, we must create our Ruby classes. By sticking to our naming conventions Active Record will establish the relationship between both class and table.
class Book < ActiveRecord::Base
end
Essentially this is all you need in order to establish the relationship and be able to take full advantage of Active Record's methods.
Full CRUD implementation
When working with data from a table it is important to have CRUD operations made when necessary. CRUD is used to interact with our stored data and it stands for create, read, update, and delete. Thankfully Active Record already creates many methods to allow an application to manipulate this stored data.
Some examples include:
Create
To create an Active Record object, there are a few key methods used. create
will return the object and save it to the corresponding database. While new
will simply return the object and be instantiated without being saved, the save
method will then be needed to save this object to the database.
# Create a new book and save this book to the database
Book.create(title: "The Great Gatsby")
Read
Active Record has many different methods used to access data from a database, the list can be found here. However, some common examples include:
# Read all book data from a database table and their titles
@books = Book.all
@books.each do |book|
puts book.title
end
@book = Book.first
@twilight = Book.find_by(title: "Twilight")
Update
Once you find the data needed, its attributes can be changed and subsequently saved back into the database using various update methods. update
method will take the object modify it to the given attributes, and then save the data to the database. However, there are other ways of accomplishing the same task shown below:
# Update an existing book
book = Book.find(21)
book.edition = ('1st')
book.save
Delete
Once an Active Record object has been retrieved it can be destroyed, removing it completely from the database. destroy
is the generic method used for deleting single objects. If more than one object will be destroyed the destroy_by
and destroy_all
methods are useful.
# Delete a book
book = Book.find(21)
book.destroy
Full Active Record documentation can be found here.
Top comments (0)