LoginSignup
5
1

More than 5 years have passed since last update.

DBのデフォルトのインデックス名を短くする「activerecord-simple_index_name」

Posted at

activerecord-simple_index_nameとは?

Railsで生成されるインデックス名からtable名を抜いて短くするためのgemです

create_table :user_stocks do |t|
  t.integer :user_id,    null: false
  t.integer :article_id, null: false
  t.timestamps null: false
end

add_index :user_stocks, [:user_id, :article_id]

こういうmigrationがあった時に、デフォルトだと index_user_stocks_on_user_id_and_article_id というindex名が作られますが、activerecord-simple_index_nameを使うと user_id_and_article_id というindex名になります

基本的な使い方

Gemfileに書いてrequireするだけ

応用的な使い方

既存のアプリに途中から activerecord-simple_index_name を導入する仕組みを用意しています

デフォルトではindex短くしつつも、特定の場所だけ無効化したい(オプトアウト)

migrationで ActiveRecord::SimpleIndexName::DisableShorten をincludeすれば一時的に無効化できます。

例)

class AddArticleIndexToUserStocks < ActiveRecord::Migration
  include ActiveRecord::SimpleIndexName::DisableShorten

  def change
    add_index :user_stocks, :article_id
  end
end

デフォルトでindex短くするやつを無効化しつつ、特定の場所で有効化したい(オプトイン)

デフォルトの挙動は設定で変えられます。

ActiveRecord::SimpleIndexName.config.auto_shorten = true

or

ActiveRecord::SimpleIndexName.configure do |config|
  config.auto_shorten = true
end

auto_shortenfalse にすれば短くならなくなります。(要はactiverecord-simple_index_nameを入れない時と同じ状態)

デフォルトだと true (自動でindex名が短くなる)です。

特定の場所のみindex名を短くするのを有効にしたい場合はさっきの逆で Activerecord::SimpleIndexName::EnableShorteninclude してください。

class AddCategoryIdToArticles < ActiveRecord::Migration
  include Activerecord::SimpleIndexName::EnableShorten

  def change
    add_column :articles, :category_id, :integer
    add_index :articles, :category_id
  end
end

元ネタ

ActiveRecordのデフォルトのインデックス名が長いのが気になる - Qiita

kamipoさんから許可をもらってgem化しています :bow:

元エントリだと alias_method_chain を使っていますが、activerecord-simple_index_nameではRails 5対応の時に prepend を使うようにしています。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1