Reputation: 205
so i have this piece of code:
render :json => { :objects => @object.object_children }
This works. But What I only want are certain attributes only. I saw this: filter json render in rails 3 and in it is this:
respond_to do |format|
format.json { render json: @objects.object_children, :only => [:id, :name] }
end
It works, but it returns data without a label, just like this:
id":null,"name":"foo"
I want the ":objects =>" label in it. Thanks
Upvotes: 0
Views: 480
Reputation: 198
You have to combine your original solution with the one you found:
render :json => { :objects => @object.object_children.as_json(:only => [:id, :name]) }
EDIT: Explanation
In your original solution you're adding the key :objects =>
manually to the response.
render :json => @object.object_children
# vs
render :json => { :objects => @object.object_children }
So to add the key and filter the returned attributes you have to do the same but then call as_json (that's what Rails would do for simply returning the whole collection) manually with the :only
option to apply the filter.
If you use the respond_to
block depends on your needs.
Upvotes: 1
Reputation: 4555
For advanced json serialization, check out Active Model Serializers
Upvotes: 2