Using a different key name for association attribute in rails api active model serializer

I am creating a Rest API using rails-api and active-model-serializer to easily filter out the required fields in JSON. I also use the has_one association in these serializers. All I wanted to know was how to specify a different key name for the has_one attribute.

That is, I have two models: Employee and Address , and << 24> - EmployeeSerializer . The answer I get is:

 { id: 1, address: { street: "some_street", city: "some_city" } } 

But I would like to get the following answer:

 { id: 1, stays: { street: "some_street", city: "some_city" } } 

I tried using has_one :address, :key => :stays , but this does not work.

+7
json ruby-on-rails rails-api active-model-serializers
source share
2 answers

You can define stays as one of the attributes you want to use in json.

Naturally, the serializer will go to the model instance and will not find an attribute in the model with this name. Thus, he will sit there, scratching his head as to what the world should mean :stays .

This is good because you can define an instance method in your serializer by specifying exactly what this value should be. In this case, you are provided with the variable object , which is the object that the serializer processes. object.address therefore will be your copy of Address .

Once you have an instance of your address, you can create an instance of the serializer that will use this instance to display the fields located inside it. I believe that root: false necessary, because otherwise the :stays attribute (or what the serializer will give you in this case) will be displayed inside another attribute :stays .

Your last serializer for Employee should look like this:

 class EmployeeSerializer < ActiveModel::Serializer attributes :id, :name, :stays def stays MyAddressSerializer.new(object.address, root: false) end end 
+7
source share

@janfoeh is right. 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 server backup

It works great!

As the documentation for the gem says ( here ), you probably want to use version 0.8 "

+3
source share

All Articles