ruby-on-rails-3.1respond-with

How to respond_with multiple objects in Rails 3.1


I have a route for example

POST /interaction.json

where the client posts a new interaction. Normally my controller would look like

class InteractionController < ApplicationController

    def create
        respond_with @log
    end

end

and I will get back a json response

{ "log" : { "id" : 20, .... } }

and the location header set to

http://foo.com/log/20

However if I wish to return more objects in my :json response than just the @log. For example to notify the client that some thing has changed with respects to this interaction the normal. Perhaps the user has won a prize for making this interaction. It would be nice to be able to do

response_with @log, @prize

and get the response

{ "log": { "id": 20, ... },
  "prize": { "id": 50, ...}
}

but that is not the way respond_with works. It treats @prize as a nested resource of @log. Can anyone suggest an idea for this?


Solution

  • Merging two independent objects is dangerous and will override any existing attributes in the caller.

    Instead you could always wrap the objects and respond with the wrapper instead:

    @response = {:log => @log, :price => @price}
    respond_with @response