使用多个 JSON 渲染进行响应。 (红宝石/Rails)
这是一个相对简单的方法,我很确定它的语法正确。
我试图将多个对象渲染为 json 作为控制器中的响应。像这样的事情:
def info
@allWebsites = Website.all
@allPages = Page.all
@allElementTypes = ElementType.all
@allElementData = ElementData.all
respond_to do |format|
format.json{render :json => @allWebsites}
format.json{render :json =>@allPages}
format.json{render :json =>@allElementTypes}
format.json{render :json =>@allElementData}
end
end
end
问题是我只得到一个 json,而且它始终是最上面的。有没有办法以这种方式渲染多个对象?
或者我应该创建一个由其他objects.to_json组成的新对象?
This is a relatively simple one and I'm pretty sure its just syntax.
Im trying to render multiple objects as json as a response in a controller. So something like this:
def info
@allWebsites = Website.all
@allPages = Page.all
@allElementTypes = ElementType.all
@allElementData = ElementData.all
respond_to do |format|
format.json{render :json => @allWebsites}
format.json{render :json =>@allPages}
format.json{render :json =>@allElementTypes}
format.json{render :json =>@allElementData}
end
end
end
Problem is I'm only getting a single json back and its always the top one. Is there any way to render multiple objects this way?
Or should I create a new object made up of other objects.to_json?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你实际上可以这样做:
如果你使用jquery,你将需要做类似的事情:
等等
编辑:
回答你的问题,你不一定要解析响应,这只是我通常做的。有许多函数可以立即为您完成此操作,例如:
you could actually do it like so:
in case you use jquery you will need to do something like:
and so on
EDIT:
answering your question, you don't necessarily have to parse the response, it's just what I usually do. There's a number of functions that do it for you right away, for example: