ActiveModel Serializer converts underscores to hyphens

Here’s the prob­lem I ran into. I setup rails in the API mode and con­fig­ured to use Active­Mod­elSe­ri­al­iz­ers and fol­low the JSON5 spec. But turns out, that con­verts all the field names in my JSON responses to con­tain hyphens instead of underscores.

The seri­al­izer was con­vert­ing the data­base field first_name into first-name in my JSON responses.

I don’t like that! I want my field names to stay the same. Untouched and pris­tine, like the frozen lakes of Antartica.

Turns out you can ask your seri­al­izer not not mess with your field names. Just add the fol­low­ing line in your active_model_serializer.rb

ActiveModel::Serializer.config.key_transform = :unaltered

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...

  • Dylan Pierce

    Thank you! Saved me oodles of time try­ing to cre­ate a cus­tom func­tion to keep my lovely underscores