Take the 2-minute tour ×

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] }

It works, but it returns data without a label, just like this:


I want the ":objects =>" label in it. Thanks

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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

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.

share|improve this answer
add comment

For advanced json serialization, check out Active Model Serializers

share|improve this answer
add comment

Your Answer


