> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/create-a-custom-named-references-column.md).

# Create A Custom Named References Column

The `t.references` and `add_reference` methods both create a foreign key column name based on the target table.

For instance,

```ruby
add_reference :guests, :user, foreign_key: true, index: true, null: false
```

would create a `user_id` column on the `guests` table.

At times, you'll need to customize the name of the foreign key column. The Rails migration DSL supports this with the `foreign_key` option.

Here is an example that shows the syntax for both a new table and an existing table.

```ruby
class AddInvitedByColumnToUser < ActiveRecord::Migration[6.1]
  def change
    create_table :guests, id: :uuid do |t|
      t.string :email, null: false
      t.timestamps

      t.references :invited_by,
        type: :uuid,
        index: true,
        null: false,
        foreign_key: { to_table: :users }
    end

    add_reference :guests, :signed_up_as,
      type: :uuid,
      index: true,
      null: false,
      foreign_key: { to_table: :users }
  end
end
```

The `t.references` call creates a foreign key column to the `users` table named `invited_by`. The `add_reference` call adds a `signed_up_as` foreign key column to `guests` that points to users.

[source](https://stackoverflow.com/a/42056089/535590)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://ploegert.gitbook.io/til/programmy/rails/create-a-custom-named-references-column.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.
