LoginSignup
23
19

More than 5 years have passed since last update.

enum の整数値を取得する

Last updated at Posted at 2017-04-20

方法

Rails 4

ActiveRecord::AttributeMethods#[] あるいは
ActiveRecord::AttributeMethods::Read#read_attribute を使います。

# Rails 4.2.8
class Conversation < ActiveRecord::Base
  enum status: [:active, :archived]
end

conversation.status #=> "archived"

conversation[:status] #=> 1
conversation.read_attribute(:status) #=> 1

conversation.read_attribute_before_type_cast(:status) #=> "1"
conversation.status_before_type_cast #=> "archived"

Rails 5

前述した Rails 4 の方法では整数値が取得できなくなりました。代わりに ActiveRecord::AttributeMethods::BeforeTypeCast#read_attribute_before_type_cast あるいは
%{カラム名}_before_type_cast という名前のメソッドを使います。

# Rails 5.0.2
class Conversation < ActiveRecord::Base
  enum status: [:active, :archived]
end

conversation.status #=> "archived"

conversation[:status] #=> "archived" 
conversation.read_attribute(:status) #=> "archived"

conversation.read_attribute_before_type_cast(:status) #=> 1
conversation.status_before_type_cast #=> 1

Rails 4 とかなり振る舞いが変わっているので、注意が必要ですね。

参考

23
19
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
23
19