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