Reacting with multiple JSON rendering. (Ruby / Rails)

This is relatively simple, and I'm sure it is just the syntax.

I am trying to display multiple objects as json as a response in the 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 

The problem is that I only get one json back and its always top. Is there a way to render multiple objects this way?

Or do I need to create a new object consisting of other .to_json objects?

+4
source share
1 answer

you could do it like this:

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

if 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 

etc.

EDIT:

When answering your question, you donโ€™t have to parse the answer, this is what I usually do. There are a number of functions that do this for you right away, for example:

 $.getJSON('/info', function(data) { var websites = data.websites, pages = data.pages, ... }); 
+14
source

All Articles