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.
class CreateJoinTableCustomerProduct < ActiveRecord::Migration
def change
create_join_table(:customers, :products)
end
end
It will create new join table customer_products
with columns customer_id
and
product_id
. We can also use block with create_join_table
.
class CreateJoinTableCustomerProduct < ActiveRecord::Migration
def change
create_join_table :customers, :products do |t|
t.index :customer_id
t.index :product_id
end
end
end
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.
class CreateJoinTableCustomerProduct < ActiveRecord::Migration
def change
create_table :customer_products do |t|
t.uuid :customer_id
t.uuid :product_id
end
end
end
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.
class CreateJoinTableCustomerProduct < ActiveRecord::Migration[5.0]
def change
create_join_table(:customers, :products, column_options: {type: :uuid})
end
end
If this blog was helpful, check out our full blog archive.