charleetm charleetm - 1 month ago 8
Ruby Question

activemodel serializer has_one with custom root name

I have a

has_one
relationship in my serializer but setting
root: :some_other_root
doesn't seem to make any difference. I see in the doc they are only using a different
root
name with
has_many
. So the question is is it possible to have a different root name on
has_one
?

given:

class UserSerializer < ActiveModel::Serializer
attributes :id
has_one :address, root: :primary_address
end


returns:

{"user":{"id": 12, "address":{"id":5,"company_name":"widgets co"}}}


expected:

{"user":{"id": 12, "primary_address":{"id":5,"company_name":"widgets co"}}}

Answer

Use key instead of root if it will be included as part of the user attributes. There's a thorough explanation on how to embed associations in the gem repo

Comments