代码之家  ›  专栏  ›  技术社区  ›  Daniel Viglione

ActiveRecord迁移中的联接表

  •  1
  • Daniel Viglione  · 技术社区  · 8 年前

    我在阅读Rails指南时发现了一种用于创建联接表的新语法:

    class CreateJoinTableCustomerProduct < ActiveRecord::Migration[5.0]
      def change
        create_join_table :customers, :products do |t|
          # t.index [:customer_id, :product_id]
          # t.index [:product_id, :customer_id]
        end
      end
    end
    

    也许这个helper方法create\u join\u table在Rails 5中是新的,并在schema.rb中生成适当的连接表。但正是这一部分让我不安:

      # t.index [:customer_id, :product_id]
      # t.index [:product_id, :customer_id]
    

    通常,如果要向列添加索引,请执行以下操作:

    add_index :products, :product_id 
    

    1 回复  |  直到 8 年前
        1
  •  2
  •   max Mike Williams    8 年前

    t.index [:customer_id, :product_id]
    

    传递一个数组将创建一个复合索引,该索引对两列的组合进行索引,这正是连接表的含义。

    例如,这可用于强制值组合的唯一性:

    t.index [:user_id, :coupon_id], unique: true
    

    或者只是加快查询速度。

    Rails创建两个独立索引的原因:

    # t.index [:customer_id, :product_id]
    # t.index [:product_id, :customer_id]
    

    顺序实际上关系到性能—对于b树索引,一个非常简单的经验法则是,应该首先放置最有选择性的列。您应该为您的用例选择最佳的复合索引。

    请参见: