背景
rails 5でpostgresでjsonのdefaultに[]
としていたが、Dockerで起動してnewしてみると、'[]'
となった!
DockerのPostgresをチェック
versionチェック
docker-compose run --rm db bash
bash-4.3# psql --version
psql (PostgreSQL) 9.6.7
テーブルチェック
postgresの中身を直接見てみる docker上で動かしているpostgresに接続する
テーブルの中身を見てみる
\c <database_name>
\d <table_name>
id | integer | not null default ..
name | character varying | not null
data | json | not null default '"[]"'::json
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
なんと、default '"[]"'::json
となっていた!
Dockerでない方をチェック
versionチェック
psql postgres
psql (9.6.3)
テーブルチェック
\c <database_name>
\d <table_name>
Column | Type | Modifiers
---------------+-----------------------------+-----------------------------------------------------
id | integer | not null default
name | character varying | not null
data_type | character varying | not null
data | json | not null default '[]'::json
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
こっちは、default '[]'::json
!!これが原因!
PostgresのVersionが違うせい?
関連記事を見つけたので呼んでみた。defaultを{}
にしている場合にrailsに確かにバグがあったらしい。
Postgres JSONB column is returned as string instead of hash in Rails 5 RC2
https://github.com/rails/rails/issues/25594
Rails 5 AR migrations: default value for json type columns
https://github.com/rails/rails/issues/26101
when to use "[]" as default instead of "{}" ?
が一番最後にあるが、返信がないので、これが関係してそうだが、ローカルでRails5.0.0でsetupしたときには、問題なく'[]'
となっていた。
解決策
Gemのバージョンがもしかしたら修正前なんじゃないかということで、vendor/bundle以下を全部削除して、bundle install
し直してから、Dockerを立ち上げるとうまく言った。 db/schema.rbにも変化なくいけた。Dockerとは関係ない問題だったかもしれない。