指定一个Rails的属性对象传递到一个JSON对象 [英] Specifying attributes of a Rails object passed into a JSON object
问题描述
我在Rails的一个对象具有属性A,B,C,D和E.当通过这个对象返回给客户端通过JSON对象,我怎么能告诉导轨控制器只包含一个属性并在JSON对象D'
在我的用户控制器,我的code是如下:
@user = User.find(PARAMS [:ID]) 做的respond_to |格式|
format.html
format.json {渲染:JSON => @用户}
结束
这code工作,然而,返回的JSON对象包含@user对象的所有属性。我怎么能限制包括在JSON对象的属性之前发送任何内容返回给客户端?
更新:lucapette提供有关发生了什么幕后的一些良好的背景。因为有次我可能希望返回所有属性的时候,我结束了使用以下code:
format.json {渲染:JSON => @ user.to_json(:只=>身份证])}
渲染:JSON => @用户
将调用 to_json
的@user对象。和 to_json
方法将使用 as_json
的方法做其工作。所以,你可以很容易地覆盖 as_json
来只有你想要给客户什么通过。就像下面这个:
高清as_json选项= {}
{
ATTR1:ATTR1,
attR2位:attR2位
}
结束
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"])}
render :json => @user
will call to_json
on the @user object. And the to_json
method will use the as_json
method to do its work. So you can easily override the as_json
to pass only what you want to the clients. Like in the following:
def as_json options={}
{
attr1: attr1,
attr2: attr2
}
end
这篇关于指定一个Rails的属性对象传递到一个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!