LoginSignup
5
6

More than 5 years have passed since last update.

create_tableのブロックだけでDBにユニークインデックスを貼れないのか?

Last updated at Posted at 2017-09-28

疑問

  • create_tableのブロックだけでDBにユニークインデックスを貼れないの?
    • RailsDocでは触れられてない…
    • こういうSOの記事とかあるけど本当にできないの?

結論

add_index と同じオプションが使える
-> t.string :column_name, index: { unique: true } と書ける

Railsのコード読んでみた

  • 環境:Rails 5.1.1

create_table のブロック内部

  • 前段

    • ブロック引数は class TableDefinition のインスタンス。
    • t.string t.integer などは t.column(name, type, options = {}) のシンタックスシュガー
    • (module ColumnMethodsあたりを参照)
  • create_table のカラム追加メソッド

  def column(name, type, options = {})
    ...
    index_options = options.delete(:index)
    index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
    ...
  end
  • indexの定義
  # Adds index options to the indexes hash, keyed by column name 
  # This is primarily used to track indexes that need to be created after the table 
  # 
  #   index(:account_id, name: 'index_projects_on_account_id') 
  def index(column_name, options = {})
      indexes << [column_name, options]
  end

create_table メソッド

create_tableじゃない方法で作成する時と同じadd_indexを呼んでいる

def create_table(table_name, comment: nil, **options)
  ...
  td.indexes.each do |column_name, index_options|
    add_index(table_name, column_name, index_options)
  end
end

つまり

add_indexで指定できるものはcreate_table内でも使える!

5
6
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
6