class User < ApplicationRecord
enum status: [ :active, :inactive ]
end
默认情况下,主动型串行序列化User
对象的status
属性为一个字符串,要么"active"
或"inactive"
,但我想它是整数0
或1
。要做到这样,我必须手动做到这一点:如何让主动型串行自动转换枚举属性为整数
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
这是一个有点难看,因为我必须编写代码为每个活动模型类每个枚举属性。有没有选择做一次?
感谢您指出。我意识到了这一点,但是我正在寻找一个让AMS自动执行此操作的选项,否则将在序列化程序定义中为每个枚举属性设置一个方法,如上例中的'status'。 – user10375