Specifying attributes of a Rails object passed into a JSON object

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

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

回答1:

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 


回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!