Rails 3 respond_with json question

Mike Jaffe picture Mike Jaffe · May 11, 2011 · Viewed 17.7k times · Source

Having trouble with generating some json. I am trying to render an single active record result to json like this:

@data = User.find(1)
respond_with(@data, :include => :status)

The json result is:

{
  -user: {
    address: null
    email: "[email protected]"
    first_name: "Test"
    last_name: "Man"
    status_id: 1
    username: "testguy"
    status: { }
  }
}

So whats the problem? The problem is that the :include=>:status seems to not bring over the relation. In my User model I have a belongs_to :status. How do i get this to work on a single result set?

When I do this:

@data = User.where("id = 1")
respond_with(@data, :include => :status)

The relation shows in the json result set fine this way. But its within an array of objects, which i do not want.

Any ideas?

Answer

mdziurla picture mdziurla · Jan 19, 2012

I assume that the status you want to include is not one of the http status codes (200, 201, etc.) nor an object associated with the User object in any way and is your own variable.

Using Rails 3.0.10 and Ruby 1.9.2 you may have find one of these two solutions suitable for you. Instead of respond_with use render as follows.

Solution 1

render :json => {:data => @data, :status => "whatever"}

The json result is:

{
  data:
  {
    user:
    {
      address: null
      email: "[email protected]"
      first_name: "Test"
      last_name: "Man"
      status_id: 1
      username: "testguy"
    }
  }
  status: "whatever"
}

Solution 2

render :json => {:user => {:address => @data.address, :email => @data.email, ..., :status => "whatever"}}

The json result is:

{
  user:
  {
    address: null
    email: "[email protected]"
    ...
    status: "whatever"
  }
}

I hope this is what you were looking for.