指定传递到 JSON 对象的 Rails 对象的属性
我在 Rails 中有一个对象,它具有属性 A、B、C、D 和 E。当通过 JSON 对象将该对象传递回客户端时,如何告诉 Rails 控制器仅在其中包含属性 A 和 D JSON 对象?
在我的 Users 控制器中,我的代码如下:
@user = User.find(params[:id])
respond_to do |format|
format.html
format.json { render :json => @user}
end
该代码有效,但是返回的 JSON 对象包含 @user 对象的所有属性。在将任何内容发送回客户端之前,如何限制 JSON 对象中包含的属性?
更新:lucapette 提供了一些关于幕后发生的事情的良好背景。由于有时我可能希望返回所有属性,因此我最终使用了以下代码:
format.json { render :json => @user.to_json(:only => ["id"])}
I have an object in Rails that has attributes A, B, C, D, and E. When passing this object back to the client-side through a JSON object, how can I tell the rails controller to only include attributes A and D in the JSON object?
Within my Users controller, my code is as follows:
@user = User.find(params[:id])
respond_to do |format|
format.html
format.json { render :json => @user}
end
This code works, however, the JSON object that is returned contains all the attributes of the @user object. How can I limit the attributes that are included in the JSON object before anything is sent back to the client?
UPDATE: lucapette provides some good background about what's happening behind the scenes. Since there are times when I'd probably want all attributes returned, I ended up using the following code:
format.json { render :json => @user.to_json(:only => ["id"])}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将在@user对象上调用
to_json
。to_json
方法将使用as_json
方法来完成其工作。因此,您可以轻松覆盖as_json
以仅将您想要的内容传递给客户端。就像下面这样:will call
to_json
on the @user object. And theto_json
method will use theas_json
method to do its work. So you can easily override theas_json
to pass only what you want to the clients. Like in the following:这里的好方法 如何从模型中仅选择特定属性?
使用 select 来获取某些属性。
当然,仅当您不需要代码中的其他属性时才有效。
作为解决这个问题的通用方法,rabl 值得一看 https://github.com/nesquena/rabl< /a>
Nice way over here How to select only specific attributes from a model?
using select to just get certain attributes.
Off course only works if you don't need the other attributes in code.
As a general way to attack this problem, rabl is worth a look https://github.com/nesquena/rabl