問題描述
如何將 ActiveModel::Serializer :has_many 關聯的密鑰格式(即駝峰式)指定為一次性選項(不是全局配置)? (How to specify the key format (i.e. camelcase) for an ActiveModel::Serializer :has_many association as a one‑off option (not global config)?)
我有一個這樣的序列化程序:
class FooSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :foo_bars, serializer: BarSerializer
end
class BarSerializer < ActiveModel::Serializer
attributes :id, :acronym
end
我的問題是,當實例化序列化程序並在其上調用 as_json
時,我得到以下信息:
$ foo = Foo.first
$ s = FooSerializer.new(foo)
$ s.as_json
$ => {
:foo => {
:id => 1,
:name => "Foo",
:foo_bars => [
{
:id => 1,
:acronym => "F1",
},
{
:id => 2,
:acronym => "F2",
},
]
}
}
但我的前端 API 期望接收駝峰式 fooBars
而不是蛇形 foo_bars
。如何配置序列化程序以輸出 foo_bars
與鍵 fooBars
參考解法
方法 1:
(posted this because I figured this out myself, but couldn't find the answer anywhere and hope this helps someone else, or even myself when I inevitably google this again someday...)
Pretty easy to do. Just add the key
option to your serializer's has_many
class FooSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :foo_bars, serializer: BarSerializer, key: :fooBars
end
Done. Now your serializer will output the has_many with fooBars
instead of foo_bars