Search code examples
ruby-on-railsdatabasemodelrails-migrations

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?


Solution

  • 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.