MMachinegun
MMachinegun

Reputation: 3074

Creating Join-Table with indexes in Rails

When I want to create a join-table what I read from rubyguides is that I can set the index directly as follows:

create_join_table :products, :suppliers do |t|
  t.index [:product_id, :supplier_id]
  t.index [:supplier_id, :product_id]
end

But when searching more on the topic I read I should add the index after the table is created:

add_index(:products_suppliers, [:product_id, :supplier_id], :unique => true)

Does Rails (4) understand the first approach or is it better to add the index after my table is created?

Would my two examples provide the same index or are they two different ones?

Upvotes: 1

Views: 1135

Answers (1)

MMachinegun
MMachinegun

Reputation: 3074

Okay, as @Jason pointed out I tried both ways and it turns out it works just the same :)

create_join_table :products, :suppliers do |t|
    # either directly here
    t.index [:product_id, :supplier_id], :unique => true
end

# or afterwards, both work
add_index(:products_suppliers, [:product_id, :supplier_id], :unique => true)

even defining uniqueness works in the first example.

Upvotes: 1

Related Questions