Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
bradgonesurfing Avatar asked Dec 27 '22 14:12

bradgonesurfing


2 Answers

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
like image 185
Ryan Mohr Avatar answered Jan 18 '23 08:01

Ryan Mohr


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.

like image 37
Alex Avatar answered Jan 18 '23 09:01

Alex