简体   繁体   中英

How can I return json data from multiple rails Models?

I have created a backend rails server that strictly serves an iOS app I built. Upon initial loading of the iOS app, it needs to immediately pull in about a dozen models and their data. I want to avoid 1) A dozen separate server calls and b) Chaining the dozen calls in completions blocks. IE Call A, when A is done, call B, when B is done, call C... etc.

I would like to make a Load resource. Something that will return the data from all dozen models in one call. So the resulting json will be something like...

{
    "widgets": [
        {
            "id": 1,
            "desc": "One"
        },
        {
            "id": 2,
            "desc": "Two"
        }
    ],
    "gadgets": [
        {
            "id": 1,
            "desc": "One"
        }
    ],      
    "flidgets": [
        {
            "id": 1,
            "desc": "One"
        }
    ]
}

I would also prefer to not include the timestamps.

How can I do this? Suppose I create a new controller, InitialLoadController. Then I get the model data of my dozen objects. How can I render the dozen models to json and format it like this?

Please check the code below:

class InitialLoadsController < ApplicationController
  def load
    widgets = Widget.select(:id, :desc)
    gadgets = Gadget.select(:id, :desc)
    flidgets = Flidget.select(:id, :desc)
    response = {
      widgets: widgets,
      gadgets: gadgets,
      flidgets: flidgets
    }
    render json: response
  end

end

Even you can use jbuilder to render json response (as an alternative to render json: response).

Assume you have dashboard action you can use below code to return json data from multiple model.

def dashboard
    @widgets = Widget.all
    @gadgets = Gadget.all
    @flidgets = Flidget.all

     respond_to do |format|
      format.json {
        render :json => {
           :widgets => @widgets.to_json(:except => [:created_at,:size]),
           :gadgets => @gadgets.to_json(:except => [:created_at,:type]),
           :flidgets => @flidgets.to_json(:except => [:created_at,:type])
        }
      }
     end
end

Note:- @widgets.to_json(:except =>[:created_at,:type]) this will return json without fields created_at and type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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