Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying attributes of a Rails object passed into a JSON object

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"])}
like image 856
Vee Avatar asked Jan 29 '12 18:01

Vee


1 Answers

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
like image 108
lucapette Avatar answered Sep 28 '22 16:09

lucapette