Skip to content

Associations

Anton Maminov edited this page Nov 9, 2022 · 2 revisions

The belongs_to Association

A belongs_to association sets up a connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:

class Book
  include Clear::Model

  primary_key

  belongs_to author : Author

  column name : String
end
classDiagram
  class books {
    id bigserial
    author_id bigserial
    name string
    created_at timestamp
    updated_at timestamp
  }
    
  class authors {
    id bigserial
    name string
    created_at timestamp
    updated_at timestamp
  }

  books --|> authors
Loading

The corresponding migration might look like this:

class CreateBooks
  include Clear::Migration

  def change(dir)
    dir.up do
      create_table(:authors) do |t|
        t.column :name, :string, null: false
        t.timestamps
      end

      create_table(:books) do |t|
        t.references to: "authors", name: "author_id", on_delete: "cascade", null: false, primary: true

        t.column :name, :string, null: false
        t.timestamps
      end

    dir.down do
      execute("DROP TABLE books")
      execute("DROP TABLE authors")
    end
  end
end
Clone this wiki locally