2017-09-27 18 views
0
class User < ApplicationRecord 
    enum status: [ :active, :inactive ] 
end 

默认情况下,主动型串行序列化User对象的status属性为一个字符串,要么"active""inactive",但我想它是整数01。要做到这样,我必须手动做到这一点:如何让主动型串行自动转换枚举属性为整数

class UserSerializer < ActiveModel::Serializer 
    attributes :status 
    def status 
    object.status_before_type_cast # get integer 
    # or User.statuses[object.status], the same thing 
    end 
end 

这是一个有点难看,因为我必须编写代码为每个活动模型类每个枚举属性。有没有选择做一次?

回答

0

您可以访问枚举索引值如哈希

User.statuses[:active] 
=> 0 
User.statuses[:inactive] 
=> 1 

我希望这是你在寻找什么

http://api.rubyonrails.org/v5.1/classes/ActiveRecord/Enum.html

+0

感谢您指出。我意识到了这一点,但是我正在寻找一个让AMS自动执行此操作的选项,否则将在序列化程序定义中为每个枚举属性设置一个方法,如上例中的'status'。 – user10375

0

枚举状态:{活跃:0,未激活: 1}

Model.statuses # Pluralized version of the enum attribute name 

返回哈希像:

=> { “活性”=> 0, “不活动”=> 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/

+0

这并不能解决为其序列化程序类中的每个活动模型类的每个枚举属性编写代码的问题。 – user10375