使用多个JSON渲染进行响应.(红宝石/ Rails)的

ove*_*one 4 ruby model-view-controller json controller ruby-on-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 
Run Code Online (Sandbox Code Playgroud)

问题是我只回到了一个json,它始终是最重要的一个.有没有办法以这种方式渲染多个对象?

或者我应该创建一个由其他objects.to_json组成的新对象?

Vla*_*ich 14

你实际上可以这样做:

format.json {
   render :json => {
      :websites => @allWebsites,
      :pages => @allPages,
      :element_types => @AllElementTypes,
      :element_data => @AllElementData
   }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用jquery,您将需要执行以下操作:

data = $.parseJSON( xhr.responseText );
data.websites #=> @allWebsites data from your controller
data.pages #=> @allPages data from your controller
Run Code Online (Sandbox Code Playgroud)

等等

编辑:

回答你的问题,你不一定要解析回答,这正是我通常做的事情.有很多功能可以立即为您完成,例如:

$.getJSON('/info', function(data) {
  var websites = data.websites,
      pages = data.pages,
      ...

});
Run Code Online (Sandbox Code Playgroud)