Using a different key name for an association attribute in rails api active model serializer
You can define stays
as one of the attributes you want to have in your json.
Naturally, the serializer will go to the model instance and not find an attribute in the model with that name. So, it will be sitting there scratching its head as to what in the world the value of :stays
should be.
That's OK, because you can define an instance method in your serializer telling it exactly what that value should be. In that instance method, you are given object
variable which is the object the serializer is currently processing. object.address
therefore will be your Address
instance.
Once you have your address instance, you can instantiate a serializer which will use that instance to display the fields outlined inside of it. I believe, root: false
is necessary as otherwise, :stays
attribute (or whatever the serializer gives you back in this case) will be displayed inside another :stays
attribute.
Your final serializer for Employee
should look as follows:
class EmployeeSerializer < ActiveModel::Serializer attributes :id, :name, :stays def stays MyAddressSerializer.new(object.address, root: false) endend
@janfoeh is right on. I just tested this in version 0.8 and it works just fine
gem "active_model_serializers", "~> 0.8.0"
in your Gemfile- Kill the server
$bundle install
has_one :address, key: "stays"
- Start the server back up
Works great!
As the documentation for the gem says (here), "you probably want to use version 0.8"
From 0.10.0 as of April 2016 (thanks to @AlfredoGallegos in the comments)
The answer posted will not work for 0.10.0 +
Use this instead:
ActiveModel::Serializer::CollectionSerializer.new (object.my_has_many_assoc, each_serializer: MySerializer)
Also it seems most people are moving to the Netflix JSONAPI gem, it has more support and is 25 times faster (however please note it does not support the JSON default setting of AMS).