Home > Software engineering >  How can I serialize an array of valus instead of objects
How can I serialize an array of valus instead of objects

Time:10-21


I have those two models Article and Tags [![enter image description here][1]][1]

enter image description here

I Create those serializers for each model enter image description here enter image description here

Here when I call the /articles api it returns like this which is logic since I put name attribute on my tag serializer enter image description here

How can I make the tagList field returns an array of values instead of objects so it will be like this tagList = ['hola','test','react','angular']

I'm using ruby 3.1 and rails 7.0 and ActiveModelSerializer

Any help please??!

CodePudding user response:

Instead of calling the TagSerializer for tagList, you can define a method in ArticleSerializer to return an array of tag names. Like you did for favoritesCount.

CodePudding user response:

Just remove this line from your ArticleSerializer

has_many :tags, key: "tagList", serializer: TasSerializer

and add the following method to your ArticleSerializer

def tags
  object.tags.map(&:name)
end

and add tags to the list of attributes that should be rendered:

attribute :tags
  • Related