Rails数据库索引 #

一、索引基础 #

1.1 创建索引 #

ruby
# 迁移中创建索引
class AddIndexesToArticles < ActiveRecord::Migration[7.1]
  def change
    add_index :articles, :title
    add_index :articles, :user_id
    add_index :articles, [:user_id, :status], name: 'index_articles_on_user_and_status'
  end
end

1.2 唯一索引 #

ruby
add_index :users, :email, unique: true

二、复合索引 #

2.1 创建复合索引 #

ruby
add_index :articles, [:user_id, :status, :created_at]

2.2 索引顺序原则 #

  • 最常用查询条件的列放在前面
  • 选择性高的列放在前面

三、索引类型 #

3.1 B-tree索引(默认) #

ruby
add_index :articles, :title

3.2 全文索引 #

ruby
add_index :articles, :body, using: :gin

四、总结 #

4.1 核心要点 #

要点 说明
基本索引 add_index
唯一索引 unique: true
复合索引 多列索引
索引顺序 查询频率和选择性

4.2 下一步 #

现在你已经掌握了数据库索引,接下来让我们学习 Active Record基础,深入了解Rails的ORM系统!

最后更新:2026-03-28