简体   繁体   English

在Rails 3中过滤json渲染

[英]filtering the json render in rails 3

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: 我看到了: 在rails 3中过滤json渲染 ,它是这样的:

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. 我想要其中的“:objects =>”标签。 Thanks 谢谢

对于高级json序列化,请查看Active Model序列化器

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. 在原始解决方案中,您将键:objects =>手动添加到响应中。

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. 因此,要添加键过滤返回的属性,您必须执行相同的操作,然后使用:only选项手动调用as_json(这是Rails为简单地返回整个集合所做的事情)以应用过滤器。

If you use the respond_to block depends on your needs. 是否使用respond_to块取决于您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM