In this tutorial I will show you how to create a one-to-one relationship in Ruby on Rails. There are some cases you will need to use a one-to-one relationship, where one record in table A has a record in table B and vice versa.

Related: Ruby on Rails one-to-many Tutorial
Related: Ruby on Rails many-to-many Tutorial


The one-to-one relationship is described below:

Where a Profile object has_one Image, and Image belongs_to Profile.

Ruby on Rails describes a one-to-one relationship using has_one and belongs_to.

Setup The Relationship

Database

# profiles table
create_table :profiles do |t|
  t.string :name
end
# images table
create_table :images do |t|
  t.integer :profile_id
end

Defining The Relationship In Your Model

# models/profile.rb
class Profile < ActiveRecord::Base
  has_one :image
end
# models/image.rb
class Image < ActiveRecord::Base
  belongs_to :profile
end

Using The Relationship

Now with your one-to-one relationship you will have access to a few methods in Rails.

# assign image to a profile
@profile.image = image
 
# check if object exists
if(@profile.image.nil?)
  ...
end