【问题标题】:Join tables in ActiveRecord Migrations在 ActiveRecord 迁移中连接表
【发布时间】:2019-03-17 04:25:42
【问题描述】:

我在阅读 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

也许这个辅助方法 create_join_table 是 Rails 5 中的新方法,它在 schema.rb 中生成适当的连接表。但正是这部分让我感到不安:

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

通常,如果您想为列添加索引,您可以执行以下操作:

add_index :products, :product_id 

但是为什么在这个迁移中有两个索引,具有相同的两列?这个语法的解释是什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    数据库索引不限于单列。

    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-tree 索引的一个非常简单的经验法则是,您应该首先放置最具选择性的列。您应该为您的用例选择最佳复合索引。

    见:

    【讨论】:

    • “复合索引”是关键。
    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多