0

I have created a rails migration that build a join table and the migration file looks like the picture below.

  def change
    create_join_table :users, :brands do |t|
      t.index [:user_id, :brand_id]
      # t.index [:brand_id, :user_id]
    end
  end
end

I was curious as to what the difference was between the commented out t.index and the uncommented one. I understand it at some level but wanted a better explanation of the implications as a result of the two.

1 Answers1

0

So if you check the resulting schema.rb you can see that the difference is not so big:

    create_join_table :users, :brands do |t|
      t.index [:user_id, :brand_id]
    end

creates

create_table "brands_users", id: false, force: :cascade do |t|
  t.bigint "brand_id", null: false
  t.bigint "user_id", null: false
  t.index ["brand_id", "user_id"], name: "index_brands_users_on_brand_id_and_user_id"
end

but

    create_join_table :users, :brands do |t|
      t.index [:brand_id, :user_id]
    end

creates

create_table "brands_users", id: false, force: :cascade do |t|
  t.bigint "brand_id", null: false
  t.bigint "user_id", null: false
  t.index ["user_id", "brand_id"], name: "index_brands_users_on_user_id_and_brand_id"
end

the index name slightly changes (it takes the table names in alphabetic order and then key names in the order they were declared) and the actual index changes -> key order is different.

Now how important that is? There is a very detailed stackoverflow question + answers about it that you can refer to:

https://stackoverflow.com/a/2292716/1404905

beniutek
  • 1,672
  • 15
  • 32