Hungry Beast
Hungry Beast

Reputation: 3735

Specify column name in create_table in Rails migration belongs_to column

I am creating the following table:

create_table(:categories) do |t|
  t.belongs_to :user, null: false, foreign_key: true, index: true
  t.uuid :uuid, unique: true, null: true, index: true
  t.string :kind, :limit => 32, null: false, index: true
  t.string :category, null: false, index: true
  t.datetime :deleted_at, null: true, index: true
  t.timestamps null: false, index: false

  t.index [:kind, :category], :unique => true
end

The first column is a foreign key and will by default be named "user_id". I want to create the column with the belongs_to but specify the column name as "created_by_user_id". How can I do this?

Upvotes: 1

Views: 1273

Answers (2)

amrrbakry
amrrbakry

Reputation: 599

You can pass the name of the foreign key column to foreign_key like this:

create_table(:categories) do |t|
  t.belongs_to :user, null: false, foreign_key: 'created_by_user_id', index: true
  ...
end

Upvotes: 1

uno_ordinary
uno_ordinary

Reputation: 458

I guess the solution you are looking for is explicitly creating an int or bigint column, depending on your database.

So it will be something like:

create_table(:categories) do |t|
  t.integer :created_by_user_id, null: false, foreign_key: true, index: true
...

Upvotes: 0

Related Questions