1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecord::Enumのbefore_type_castは必ず数値を返すわけじゃない

Posted at
class Monster < ActiveRecord::Base
  enum element: [ :fire, :water, :dark ]
end

こんなモデルがあったとして、

monster = Monster.new
monster.element = 1
monster.element # => "water"
monster.element_before_type_cast #=> 1

という挙動をするのでenumの数値を取るときに使われがち。

しかし、

monster = Monster.new
monster.element = :fire
monster.element # => "fire"
monster.element_before_type_cast #=> :fire

シンボルで代入するとbefore_type_castはシンボルを返す。
素直にMonster.elements[monster.element]とするのが無難っぽい。

そもそもとしてEnumの元の数値を使って何かするというのが微妙なのかもしれない。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?