class User < ApplicationRecord
enum status: [ :active, :inactive ]
end
默认情况下,活动模型序列化程序会将User
对象的status
属性序列化为字符串"active"
或"inactive"
,但我希望它是整数{{1 }或0
。要做到这一点,我必须手动完成:
1
这有点难看,因为我必须为每个活动模型类的每个枚举属性编写代码。有没有选择这样做一次?
答案 0 :(得分:0)
您可以像哈希
一样访问枚举索引值User.statuses[:active]
=> 0
User.statuses[:inactive]
=> 1
我希望这就是你要找的东西
http://api.rubyonrails.org/v5.1/classes/ActiveRecord/Enum.html
答案 1 :(得分:0)
枚举状态:{有效:0,无效:1}
Model.statuses # Pluralized version of the enum attribute name
返回如下的哈希:
=&GT; {&#34;有效&#34; =&gt; 0,&#34;无效&#34; =&gt; 1}
然后,您可以使用Model类实例中的状态值来访问该实例的整数值:
my_model = Model.find(123)
Model.statuses[my_model.status] # Returns the integer value
https://www.sitepoint.com/enumerated-types-with-activerecord-and-postgresql/