0
0

enumerize が適用されているカラムに定義外の値が入るとデフォルト値固定になる

Posted at

以下のように定義されている場合に

class User
  enumerize :status, in: {
    authorized: 1,
    invalid: 2,
  }, default: :authorized, scope: true
end

以下のようにレコードを登録してみる。

+-----+--------+
| id  | status |
+-----+--------+
|   1 |     99 |
+-----+--------+

このレコードを ActiveRecord を通して取得してみると

pry(main)> User.find(id: 1).status
=> "authorized"

authorized として取得される。元の値を取得しようとしても

pry(main)> User.find(id: 1).status_before_type_cast
=> 1

authorized の値になっている。デフォルトが authorized で指定されているためで default 指定をなくせば nil になる。

通常はこのような値が入ることはないが、1つの DB に対し複数のシステムから接続するとたまに規定外の値が入ることがあるため調査。

0
0
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
0
0