Search code examples
ruby-on-railsassociationshas-manyactive-model-serializerscamelcasing

How to specify the key format (i.e. camelcase) for an ActiveModel::Serializer :has_many association as a one-off option (not global config)?


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


Solution

  • (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