试图了解关系 table 的迁移顺序

Trying to understand the order of the migration for a relational table

我创建了一个 rails 构建连接的迁移 table,迁移文件如下图所示。

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

我很好奇注释掉的 t.index 和未注释的有什么区别。我在某种程度上理解它,但希望更好地解释两者的含义。

因此,如果您检查结果 schema.rb,您会发现差异并没有那么大:

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

创造

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

但是

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

创造

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

索引名称略有变化(它采用 table 名称按字母顺序排列,然后按声明顺序排列键名称) 并且实际索引发生变化 -> 键顺序不同。

现在这有多重要?有一个非常详细的Whosebug question + answers关于它你可以参考: