Most of the time, it's a good default to add a unique index on the foreign key when using Rails’ has_one relationship. This ensures the database enforces the 1:1 constraint and raises an error if your application logic ever violates it.
class User < ApplicationRecord
  has_one :session, dependent: :destroy
end
class Session < ApplicationRecord
  belongs_to :user
end
create_table :users do |t|
  t.timestamps
end
create_table :sessions do |t|
  t.references :user, null: false, foreign_key: true, index: { unique: true } # Don't forget the uniqueness here
  t.timestamps
end
Posted by Emanuel to makandra dev (2025-10-31 13:49)