bradgonesurfing
bradgonesurfing

Reputation: 32182

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?

Upvotes: 4

Views: 4257

Answers (2)

Ryan Mohr
Ryan Mohr

Reputation: 821

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

Upvotes: 9

Alex
Alex

Reputation: 9471

Assuming that @log and @prize are both hashes, you could merge both hashes and return the merge.

respond_with @log.merge(@prize)

I'm thinking it might overwrite the @log.id with @prize.id though. Can try something else if it does.

Upvotes: 1

Related Questions