Ruby on Rails is a powerful web development framework that allows developers to quickly build robust and scalable applications. One of the key components of Rails is ActiveRecord, an ORM (Object-Relational Mapping) library that simplifies database operations. In this article, we will explore how to work with databases using ActiveRecord in a Ruby on Rails application.
Before we dive into working with databases, let's make sure we have ActiveRecord set up in our Rails application. First, we need to define the database connection in the config/database.yml
file. This file contains the configuration details for different environments (development, test, and production). Make sure to specify the correct adapter, database name, username, and password.
Next, we need to create a model that corresponds to a database table. Models in Rails are subclasses of the ActiveRecord::Base
class. Let's say we have a table called "users" in our database. We can create a corresponding model by running the following command:
rails generate model User
This will generate a migration file under db/migrate
directory and a model file under app/models
directory. The migration file contains instructions for creating the "users" table, while the model file contains the ActiveRecord class definition.
Migrations are used to manage database schema changes over time. They are Ruby files that use ActiveRecord's DSL (Domain Specific Language) to define changes to the database structure. To create a migration, we can use the following command:
rails generate migration AddNameToUser name:string
This will generate a new migration file under db/migrate
directory. The migration file will contain a change
method that defines the changes to be made to the database. In this case, it adds a "name" column of type string to the "users" table.
To apply the migration and update the database schema, we run the following command:
rails db:migrate
This will execute all pending migrations and update the database accordingly. Migrations can also be rolled back using the db:rollback
command.
ActiveRecord provides an intuitive API for performing CRUD (Create, Read, Update, Delete) operations on database records. Let's take a look at some examples:
To create a new record, we can instantiate a new instance of the model class and set its attributes. For example:
user = User.new(name: "John Doe", email: "john.doe@example.com")
user.save
This will create a new record in the "users" table with the specified attributes.
To fetch records from the database, we can use various ActiveRecord methods like find
, where
, and all
. For example:
# Find a record by id
user = User.find(1)
# Find records that match a condition
users = User.where(age: 25)
# Fetch all records
all_users = User.all
To update a record, we can fetch it from the database and modify its attributes. For example:
user = User.find(1)
user.name = "Jane Doe"
user.save
This will update the "name" attribute of the record with id 1.
To delete a record, we can simply call the destroy
method on the record. For example:
user = User.find(1)
user.destroy
This will remove the record with id 1 from the database.
ActiveRecord provides powerful support for defining and working with associations between models. Associations allow us to establish relationships like one-to-many, many-to-many, etc. Let's take a brief look at how associations can be defined:
class User < ActiveRecord::Base
has_many :posts
has_many :comments, through: :posts
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
In the above example, a user has many posts, a post belongs to a user, and a post has many comments. We can now perform operations like fetching a user's posts or a post's comments with ease using ActiveRecord's association methods.
ActiveRecord is a powerful library in Ruby on Rails that simplifies working with databases. It provides an intuitive API for performing CRUD operations, managing migrations, and defining associations between models. Understanding how to work with databases using ActiveRecord is essential for building robust and scalable Rails applications.
noob to master © copyleft