【问题标题】:Trying to understand the order of the migration for a relational table [duplicate]试图了解关系表的迁移顺序[重复]
【发布时间】:2021-12-17 12:22:26
【问题描述】:

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

  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 和未注释的 t.index 之间有什么区别。我在某种程度上理解它,但希望更好地解释两者的影响。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-6.1


    【解决方案1】:

    因此,如果您检查生成的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
    

    索引名称略有变化(它按字母顺序获取表名,然后按声明顺序获取键名) 而实际的索引变化 -> 键顺序不同。

    现在这有多重要?有一个非常详细的stackoverflow question + answers,您可以参考:

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

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2018-10-27
      • 2018-07-14
      • 1970-01-01
      • 2017-01-28
      • 2016-12-22
      相关资源
      最近更新 更多