José Lezama José Lezama - 3 months ago 9
JSON Question

Json serializer different json name

I have a relationship between 2 elements. Basically, I have posts & categories.

In my approach I have 2 controllers:

PostsController
with
index, show, update, destroy & *categories*


CategoriesController
with
index


When I wanna modify the categories, I do a
POST
to the
/post/:post_id/categories
. And everything works ok. But the answer I wanna return is the categories of my post, just categories. So, I do:

render json: @post.categories,
each_serializer: CategorySerializer


And it work ok. But the answer I receive in the json is:

posts: [{id:1, title:'Category 1'}, {id:2, title:'Category 2'}]


But the desired output should be:

categories: [{id:1, title:'Category 1'}, {id:2, title:'Category 2'}]


How can I change this?

Answer

You can try this:

categories = @post.categories.map { |c| CategorySerializer.new(c) }
render json: { categories: categories }