Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

responding with multiple JSON renders. (Ruby/Rails)

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?

like image 755
overtone Avatar asked Dec 10 '22 06:12

overtone


1 Answers

you could actually do it like so:

format.json {
   render :json => {
      :websites => @allWebsites,
      :pages => @allPages,
      :element_types => @AllElementTypes,
      :element_data => @AllElementData
   }
}

in case you use jquery you will need to do something like:

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

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:

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

});
like image 67
Vlad Khomich Avatar answered Dec 26 '22 09:12

Vlad Khomich