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.
classAddUsers<ActiveRecord::Migration[7.0]defchange create_table :users do|t|# "id" primary key column will also be added implicitly by Rails(ActiveRecord) t.string :email, null: falseendendend
classAddUserProfiles<ActiveRecord::Migration[7.0]defchange create_table :user_profiles do|t| t.bigint :user_idend 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: trueendend
Resulting Model Relations
With the DB setup above, EzQL will generate the following Model Relation.
# Code generated by EzQL, DO NOT EDIT.classUser<ApplicationRecord has_one :user_profile, foreign_key: :user_id, dependent: :destroyend
# Code generated by EzQL, DO NOT EDIT.classUserProfile<ApplicationRecord belongs_to :user, foreign_key: :user_id, optional: trueend