简体   繁体   English

如何在Rails 3.1中响应多个对象

[英]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 我会得到一个json回复

{ "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. 但是,如果我希望在我的:json响应中返回更多对象,而不仅仅是@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. 但这不是response_with的工作方式。 It treats @prize as a nested resource of @log. 它将@prize视为@log的嵌套资源。 Can anyone suggest an idea for this? 任何人都可以提出这个想法吗?

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

Assuming that @log and @prize are both hashes, you could merge both hashes and return the merge. 假设@log@prize都是哈希值,您可以合并两个哈希值并返回合并。

respond_with @log.merge(@prize)

I'm thinking it might overwrite the @log.id with @prize.id though. 我想它可能会@log.id覆盖@prize.id Can try something else if it does. 如果有的话可以尝试别的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM