PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

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

 October 21, 2022     active-model-serializers, associations, camelcasing, has-many, ruby-on-rails     No comments   

Issue

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



Answered By - some_guy
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing