Reputation: 1841
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"])}
Upvotes: 11
Views: 8552
Reputation: 455
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
Upvotes: 0
Reputation: 20724
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
Upvotes: 15