José Lezama José Lezama - 1 year ago 98
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:

index, show, update, destroy & *categories*


When I wanna modify the categories, I do a
to the
. 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 Source

You can try this:

categories = { |c| }
render json: { categories: categories }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download