Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}}}
like image 571
charleetm Avatar asked Dec 26 '22 05:12

charleetm


1 Answers

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. The example looks like this:

In Serializer: attribute :title, key: :name
#attributes: { name: 'Some Title' }

like image 186
jvnill Avatar answered Jan 08 '23 04:01

jvnill