4

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
bradgonesurfing
  • 30,949
  • 17
  • 114
  • 217

2 Answers2

9

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
Ryan Mohr
  • 811
  • 8
  • 10
1

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.

Alex
  • 9,313
  • 1
  • 39
  • 44