メモ用サブブログ

子曰わく學びて時にこれを習う。

Rails 複合インデックスの使用で組み合わせの重複防止

リスト11.1 db/migrate/[timestamp]_create_relationships.rb

class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end
    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true  # <--この行が複合インデックス
  end
end

リスト11.1には複合 (composite) インデックスが使用されていることにご注目ください。これはfollower_idとfollowed_idを組み合わせたときの一意性 (uniquenes: 重複がないこと) を強制するもので、これにより、あるユーザーは別のユーザーを2度以上フォローすることはできなくなります。

Ruby on Rails チュートリアル:実例を使って Rails を学ぼう