Render :json with extra data

I have a model called Todo and I render this:

format.json { render :json => @todo }

Each Todo belongs_to a List. I want to add the value of @todo.list.completion_percentage to the JSON as I need this to update the UI (AJAX request), so the JSON looks something like this:

{
  "todo": {
    "created_at": "2011-02-26T19:39:43Z",
    "updated_at": "2011-02-26T19:53:13Z",
    "done": true,
    "text": "Apples",
    "id": 10,
    "list_id": 2,
    "user_id": 1,
    "due_date": null



    // BELOW THIS LINE SHOULD BE IMPLEMENTED
    "list": {
      "completion_percentage": 63
    }
  }
}

I have tried various things but none worked. Can anyone help me?

Answers


You may want to capture the value of the JSON data, and then modify it.

format.json { render :json => JSON::parse(@todo.to_json).merge("list" => { "completion_percentage" => 63 }).to_json }

To refine Brandon's answer, try using:

render :json => @todo.attributes.merge({list: { "completion_percentage" => 63 }})

Just so others are aware, calling @todo.attributes will pull off custom methods on attributes. E.g., if you have in your Todo model a method

    def written_date
      self.written_date = self.written_date.utc.beginning_of_day
    end 

And an attribute called written_date on the Todo Model, only the attribute will come back that is stored in the database.

And you except the custom method to come back when you call @todo.attributes, it will not.


Need Your Help

Automate distribution fitting in R

r distribution

I am trying to automate the process of fitting the most suitable distributions in R.

How do I select parent of parent of link?

javascript jquery html html5-audio playlist

I'm creating a page which I want to have multiple playlists for an player.