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
endclass 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
endResulting Model Relations
With the DB setup above, EzQL will generate the following Model Relation.
Last updated

