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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With