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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.