Rails 5 allows UUID as column type in create_join_table

Hitesh Rawal

Hitesh Rawal

June 16, 2016

This blog is part of our  Rails 5 series.

In Rails 4.x create_join_table allows us to create new join table with name given in first two arguments.

1
2class CreateJoinTableCustomerProduct < ActiveRecord::Migration
3  def change
4    create_join_table(:customers, :products)
5  end
6end
7

It will create new join table customer_products with columns customer_id and product_id. We can also use block with create_join_table.

1
2class CreateJoinTableCustomerProduct < ActiveRecord::Migration
3  def change
4    create_join_table :customers, :products do |t|
5      t.index :customer_id
6      t.index :product_id
7    end
8  end
9end
10

However create_join_table won't allows us to define the column type. It will always create column of integer type. Because Rails 4.x ,by default, supports primary key column type as an auto increment integer.

If we wish to set uuid as a column type, then create_join_table won't work. In such case we have to create join table manually using create_table.

Here is an example with Rails 4.x.

1
2class CreateJoinTableCustomerProduct < ActiveRecord::Migration
3  def change
4    create_table :customer_products do |t|
5      t.uuid :customer_id
6      t.uuid :product_id
7    end
8  end
9end
10

Rails 5 allows to have UUID as column type in join table

Rails 5 has started supporting UUID as a column type for primary key, so create_join_table should also support UUID as a column type instead of only integers. Hence now Rails 5 allows us to use UUID as a column type with create_join_table.

Here is revised example.

1
2class CreateJoinTableCustomerProduct < ActiveRecord::Migration[5.0]
3  def change
4    create_join_table(:customers, :products, column_options: {type: :uuid})
5  end
6end
7

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.