1

I have a serializer like this:

class FooSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :foo_bars, serializer: BarSerializer
end

class BarSerializer < ActiveModel::Serializer
  attributes :id, :acronym
end

My issue is that when instantiating the serializer and calling as_json on it, I get the following:

$ 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",
            },
        ]
    }
}

But my front end API expects to receive camelcase fooBars rather than snake case foo_bars. How can I configure the serializer to output the foo_bars association with the key fooBars

some_guy
  • 49
  • 8
  • Our API generally assumes snakecase, but I needed to override that in a one-off situation. If you want camelcase as your default use an initializer (see https://stackoverflow.com/questions/35437794/ruby-api-response-as-lower-camel-case/40618505#40618505) – some_guy Feb 10 '21 at 18:57

1 Answers1

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

some_guy
  • 49
  • 8
  • Can also do this in an initializer `ActiveModelSerializers.config.key_transform = :camel_lower` this is from this answer https://stackoverflow.com/a/40618505/7619578 – Int'l Man Of Coding Mystery Feb 09 '21 at 22:24
  • 1
    Good thought. I did come across that idea, but our API elsewhere generally assumes snakecase, so I needed a granular option rather than global config. But yes, that's a great (and better) solution if you want camelcase as global default setting – some_guy Feb 10 '21 at 18:53