Belongs To / Has Many

Preparing your DB schema

For defining a belongs_to and has_many relation you need to add a foreign_key to one of your two tables.

Let's define a Post belongs_to Author (one-to-one) and User has_many Posts (one-to-many)relation by adding a single foreign_key. In this example, EzQL will generate both relations.

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 AddPosts < ActiveRecord::Migration[7.0]
  def change
    create_table :posts do |t|
      t.bigint :author_id
    end

    # Define foreign key to `users.id` column from own `posts.author_id` column.
    add_foreign_key :posts, :users, column: :author_id
  end
end

Resulting Model Relations

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

# Code generated by EzQL, DO NOT EDIT.
class User < ApplicationRecord
  has_many :posts, foreign_key: :author_id, dependent: :destroy
end
# Code generated by EzQL, DO NOT EDIT.
class Post < ApplicationRecord
  belongs_to :author, class_name: "User", foreign_key: :author_id, optional: true
end