Skip to content
mengfung.com
writing

Rails 5.2 Has And Belongs To Many with UUID

 ·  1 min read

When using UUIDs and you are creating a join table like so:

rails g migration CreateJoinTableUserCompany users companies

You will get a migration file like so:

class CreateJoinTableCoverLetterCompany < ActiveRecord::Migration[5.2]
def change
create_join_table :users, :companies do |t|
#t.index [:user_id, :company_id]
#t.index [:company_id, :user_id]
end
end
end

You’ll need to modify it accordingly:

class CreateJoinTableUserCompany < ActiveRecord::Migration[5.2]
def change
create_join_table :users, :companies, column_options: { type: :uuid } do |t|
t.index [:user_id, :company_id]
t.index [:company_id, :user_id]
end
end
end

Then run:

rails db:migrate

And you should be good. Just remember if you are using UUIDs you might want to make sure all models you generate use UUIDs.

In config/application.rb:

config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end

And make sure your generated migrations have:

class CreateCompanies < ActiveRecord::Migration[5.2]
def change
create_table :companies, id: :uuid do |t|
t.string :name, limit: 80
...
end
end
end

Enjoy!