How to build a JSON response by combining @foo.to_json(options) and @bars.to_json(options) in Rails

Posted by smotchkkiss on Stack Overflow See other posts from Stack Overflow or by smotchkkiss
Published on 2010-04-03T19:11:52Z Indexed on 2010/04/03 19:13 UTC
Read the original article Hit count: 346

First, the desired result

I have User and Item models. I'd like to build a JSON response that looks like this:

{
  "user":
    {"username":"Bob!","foo":"whatever","bar":"hello!"},

  "items": [
    {"id":1, "name":"one", "zim":"planet", "gir":"earth"},
    {"id":2, "name":"two", "zim":"planet", "gir":"mars"}
  ]
}

However, my User and Item model have more attributes than just those. I found a way to get this to work, but beware, it's not pretty... Please help...


My hacks

home_controller.rb

class HomeController < ApplicationController

  def observe
    respond_to do |format|
      format.js { render :json => Observation.new(current_user, @items).to_json }
    end
  end

end

observation.rb

# NOTE: this is not a subclass of ActiveRecord::Base
# this class just serves as a container to aggregate all "observable" objects
class Observation
  attr_accessor :user, :items

  def initialize(user, items)
    self.user = user
    self.items = items
  end

  # The JSON needs to be decoded before it's sent to the `to_json` method in the home_controller otherwise the JSON will be escaped...
  # What a mess!
  def to_json
    {
      :user => ActiveSupport::JSON.decode(user.to_json(:only => :username, :methods => [:foo, :bar])),
      :items => ActiveSupport::JSON.decode(auctions.to_json(:only => [:id, :name], :methods => [:zim, :gir]))
    }
  end
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JSON