Become a Rails Association Pro: Replicating has_one with Pure Ruby

Gokul
3 min readApr 22, 2023
Become a Rails Association Pro: Replicating has_one with Pure Ruby

What?

The ActiveRecord Object Relational Mapper (ORM) is one of its most potent features. This ORM offers a straightforward user interface for interfacing with relational databases, which is another one of its strengths. The ‘has_one’ association is extremely useful in Rails since it enables users to associate one record with another record. This makes it one of the most often used associations in the framework.

But what if you want to duplicate the functionality of has_one in pure Ruby without requiring Rails or ActiveRecord? In this post on the blog, we will be exploring how to successfully carry out the aforementioned task.

Understanding the has_one Association

First, let’s take a look back at what the has_one association does in Rails. Let’s say we have a “User” model that has_one “Profile” attached to it. This indicates that each record for a “User” has a single linked record for a “Profile”, and that each record for a “Profile” belongs to a single record for a “User”. Rails enable us to define this relationship in the following way,

class User < ApplicationRecord
has_one :profile
end

class Profile < ApplicationRecord
belongs_to :user
end

--

--

Gokul

Consultant | Freelancer | Ruby on Rails | ReactJS