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
Kalman
source share