はじめに
Rails 6 に追加されそうな新機能を試す第32段。 今回は、 change_table の index オプション
編です。
Rails 6 では、 change_table
を使って、 カラムを追加するときに、 index
オプションが使えるようになっています。
Ruby 2.6.3, Rails 6.0.0.rc1, PostgreSQL 10.7 で確認しました。Rails 6.0.0.rc1 は gem install rails --prerelease
でインストールできます。
$ rails --version
Rails 6.0.0.rc1
User モデルを作る
first_name
を持つ User
モデルを作ります。
bin/rails g model User first_name
カラムを追加する
users テーブル (User モデル) に last_name
を追加します。
bin/rails g migration add_last_name_to_users
last_name
には index
オプションを追加します。
index
オプションのデフォルトは、false です。
true
にするとそのカラムのインデックスを作成します。
db/migrate/20190603125541_add_last_name_to_users.rb
class AddLastNameToUsers < ActiveRecord::Migration[5.2]
def change
change_table(:users) do |t|
t.string :last_name, index: true
end
end
end
db:migrate の実行
db:migrate
を実行します。
bin/rails db:create db:migrate
データベースを確認する
users
テーブルを psql から確認します。
app_development=# \d users
Table "public.users"
Column | Type | Collation | Nullable | Default
------------+--------------------------------+-----------+----------+-----------------------------------
id | bigint | | not null | nextval('users_id_seq'::regclass)
first_name | character varying | | |
created_at | timestamp(6) without time zone | | not null |
updated_at | timestamp(6) without time zone | | not null |
last_name | character varying | | |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"index_users_on_last_name" btree (last_name)
最後の行が
"index_users_on_last_name" btree (last_name)
となっており、 last_name
をキーにしたインデックスが作られていることがわかります。
rollback する
試しに rollback してみるとインデックスを先に削除してから、 last_name
を削除しているのがわかります。
$ bin/rails db:rollback
== 20190603125541 AddLastNameToUsers: reverting ===============================
-- remove_index(:users, {:column=>:last_name})
-> 0.0042s
-- remove_column(:users, :last_name, :string, {})
-> 0.0009s
== 20190603125541 AddLastNameToUsers: reverted (0.0150s) ======================
Rails 5 では、
Rails 5.2.3 で同じことをしても、インデックスはできません。
app_development=# \d users
Table "public.users"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+-----------------------------------
id | bigint | | not null | nextval('users_id_seq'::regclass)
first_name | character varying | | |
created_at | timestamp without time zone | | not null |
updated_at | timestamp without time zone | | not null |
last_name | character varying | | |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
試したソース
試したソースは以下にあります。
https://github.com/suketa/rails6_0_0rc1/tree/try032_index_option