8

I'm trying to return the API response as lowerCamelCase but it is not working, I need to do this for all my Controllers/fields so I need a solution for entire project.

I've tried a lot of stuff, including this (http://brentvatne.ca/automatic-casing-activemodel-serializer/) who tells me to configure Activemodel to lower_camel as following

ActiveModel::Serializer.config.key_format = :lower_camel

But that is not working, it is returning the following json

{
    "users": [{
        "id": "56b110089c28691b84a3bd73",
        "first_name": "Lucas"
    }]
}

I need to transform the first_name into firstName.

Versions:

rails -v
Rails 4.2.5

ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [i386-mingw32]

And the gems

active_model_serializers (0.10.0.rc4)
rails-api (0.4.0)

My ember App recognize the JSON but I don't want to use snake case variables on JS

engineersmnky
  • 25,495
  • 2
  • 36
  • 52
Saliba
  • 175
  • 2
  • 9
  • Are you sure that's the right json? It's got an open square bracket but no close square bracket. – Max Williams Feb 16 '16 at 16:42
  • It'd be better to put active model serializer tag to your question, since this question is specific to that gem. Also, make sure that you've restarted your rails server... it's embarrassing to admit but I've made that mistake before. – Harfangk Feb 16 '16 at 16:46
  • @Harfangk I've tried that many times, it actually hit a breakpoint on that line but does not work. – Saliba Feb 16 '16 at 19:33

3 Answers3

14

Boom! I found it! I had to dig through the AMS repo (and eventually stumbled upon a helpful readme) but here it is for v0.10:

ActiveModelSerializers.config.key_transform = :camel_lower

Put that in an initializer.

There are also other options: :dash, :camel, :underscore, and :unaltered, and nil

https://github.com/rails-api/active_model_serializers/blob/a032201a91cbca407211bca0392ba881eef1f7ba/docs/general/configuration_options.md

Aaron Krauss
  • 7,494
  • 1
  • 17
  • 19
2

The problem was on the version of Active Model Serializer (0.10.0rc2).

On the last stable version (0.9) there was an issue that has been merged to fix the camelCase but this same PR is not present on the 0.10 RC versions.

So after I have downgraded the gem it worked :)

Saliba
  • 175
  • 2
  • 9
1

Search a project for key_format in case it's overridden somewhere.

Please try it in the console, try to set key_format explicitly to make sure it's possible (ex MySerializer.new(object, key_format: :lower_camel).as_json)

If it doesn't help you can put here code example how you are using serializers.

faron
  • 1,051
  • 7
  • 9
  • This is not working in 0.10.0r4. The above code only returns an error asking for missing template. – Tom T Mar 28 '16 at 12:09