1

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?

Hungry Beast
  • 3,677
  • 7
  • 49
  • 75

2 Answers2

1

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
amrrbakry
  • 589
  • 7
  • 17
  • Oddly this doesn't work for me. It still creates the column name as user_id. Rails 4.2.10 – Hungry Beast Jan 18 '18 at 15:58
  • try adding this line: `add_foreign_key :categories, :users, column: :created_by_user_id` after the `t.belongs_to` as per this answer: https://stackoverflow.com/a/29577869/5636930 – amrrbakry Jan 18 '18 at 16:14
0

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
...
uno_ordinary
  • 458
  • 3
  • 9