カラムを追加したいとなり、どうせならきれいな位置に配置したいなと思い、
afterを使ってカラムの位置を指定してみたところ、
指定した位置に追加されなかったので調べたときの件です。
こういうテーブルをもともと用意していました。
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :name
t.string :img
t.integer :price
t.timestamps null: false
end
end
end
カラムを追加するために以下のコードを追加しました。
class AddColumnToItem < ActiveRecord::Migration
def change
add_column :items, :stock, :integer, after: :price
end
end
追加後にpostgresqlのテーブル定義を確認したところ、
stockがpriceの後ろではなく、テーブルの一番最後のカラムに追加されてしまいました。
$ psql test
psql (9.4.1)
Type "help" for help.
test=# \d items
Table "public.items"
Column | Type | Modifiers
------------+-----------------------------+----------------------------------------------------
id | integer | not null default nextval('items_id_seq'::regclass)
name | character varying |
img | character varying |
price | integer |
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
stock | integer |
Indexes:
"items_pkey" PRIMARY KEY, btree (id)
調べてみたところ、
postgresqlではそもそも列の位置を変えることができないようです。
列の位置を変えたい場合はテーブル作り直すか、
最終的なレイアウトになるまでデータを移す作業をしていくしかないようです。
これに関してはMySQLの方が柔軟でよいですね。
結局、まだ開発中のものだったので、初めからstockをpriceの後に入れたものでテーブルを作り直しました。
http://qiita.com/masamitsu-konya/items/c4f75fc02347de9f8b0f
http://stackoverflow.com/questions/27214251/postgresql-add-column-after-option-usage-in-rails-migration
http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_column#637-Options
http://dba.stackexchange.com/questions/3276/how-can-i-specify-the-position-for-a-new-column-in-postgresql
https://wiki.postgresql.org/wiki/Alter_column_position/ja
0 件のコメント:
コメントを投稿