# belongs\_to

*Belongs to* represents an association where the associated object share its primary key in a column of the current object. Let's give an example:

```sql
CREATE TABLE categories (
    id bigserial NOT NULL PRIMARY KEY, 
    name text NOT NULL
)

CREATE TABLE posts (
    id bigserial NOT NULL PRIMARY KEY,
    name text NOT NULL,
    content text,
    category_id bigint NOT NULL
)
```

In this case, Post belongs to categories, as it maintain a link to the category through `category_id` column.

In clear, this relation can be written like this:

```ruby
class Post
  include Clear::Model

  primary_key

  column name : String
  column content : String?

  belongs_to category : Category
end

class Category
  include Clear::Model
  primary_key

  column name : String

  has_many posts : Post
end
```

* Clear will take care for you of the declaration of the column `category_id`
* You may notice `has_many` in Category model. We will go further onto it in the next chapter.&#x20;

## Customizing the relation

Clear uses naming convention to infer the name of the foreign key. You may want to override this behavior by adding some parameters:

```ruby
belongs_to relation_name : RelationType, 
    foreign_key: "column_name", primary: true|false, 
    key_type: AnyType?
```

|    Argument   | Description                                                                |         Default value        |
| :-----------: | -------------------------------------------------------------------------- | :--------------------------: |
| `foreign_key` | The column used by the relation                                            | `[underscore_model_name]_id` |
|   `primary`   | Set to true if the foreign\_key is also the primary key of this table      |            `false`           |
|   `key_type`  | The type of the column. Set to the primary key type of the relative table. |           `Int64?`           |
|   `no_cache`  | Never cache the relation (note: planned feature)                           |            `false`           |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://clear.gitbook.io/project/model/associations/belongs_to.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
