Has One

Preparing your DB schema

Defining a has_one relation is almost the same as in the previous Belongs To / Has Many article. adding unique constraint(index) will mark your relation as has_one instead of has_many.

Let's define a User has_one UserProfile (one-to-one) relation for example.

class AddUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      # "id" primary key column will also be added implicitly by Rails(ActiveRecord)
      t.string :email, null: false
    end
  end
end
class AddUserProfiles < ActiveRecord::Migration[7.0]
  def change
    create_table :user_profiles do |t|
      t.bigint :user_id
    end

    add_foreign_key :user_profiles, :users, column: :user_id

    # Adding this unique constraint(index) mark this relation-
    # as "has_one" instead of "has_many".
    add_index :user_profiles, [:user_id], unique: true
  end
end

Resulting Model Relations

With the DB setup above, EzQL will generate the following Model Relation.

# Code generated by EzQL, DO NOT EDIT.
class User < ApplicationRecord
  has_one :user_profile, foreign_key: :user_id, dependent: :destroy
end
# Code generated by EzQL, DO NOT EDIT.
class UserProfile < ApplicationRecord
  belongs_to :user, foreign_key: :user_id, optional: true
end

Last updated