0

I'm doing an API in ruby on rails. I have 2 methods that returns resources in json. These 2 resources don't have any relation with each other. What I want to do is build a method to return these 2 resources in one request. What is the best way to do that without harming the restful principles? Should I maintain this way?

Edit

My files to explain myself better.

routes.rb

resources :cities, only: [:index]
resources :products, only: [:index]

cities_controller.rb

class CitiesController < ApplicationController

  respond_to :json

  def index
    @cities = City.all
    render :json => @cities
  end

end

products_controller.rb

class ProductsController < ApplicationController

  respond_to :json

  def index
    @products = Product.all
    render :json => @products
  end

end

Should I create a third controller and route to get this two resources together in one JSON? Is that the better way?

William Weckl
  • 2,435
  • 4
  • 26
  • 43

1 Answers1

0

Assuming there is a good reason these 2 resources should be presented in the same request, you could render them in such a format:

{
  "rabbit" => { ... },
  "mouse" => { ... }
}
animatedgif
  • 1,060
  • 12
  • 16
  • My reason is because a mobile APP will consume this API. It will get this infos at the same time. So, i need to do something like that to do one request instead two. But my question is not about the json format, but what is the best way to set this route and method to not harming the restful patterns. I don't know if there is any conventions of rails or restful to do something like this. – William Weckl Sep 03 '14 at 19:08
  • @WilliamWeckl it would help if you were a little more specific (what data are you loading at what time), but it sounds a little like you're preloading some data into the app. In this case I believe it would make sense to get more specific with your API action and move away from the "resource" mindset because it is not a resource oriented request.For example if you're preloading account details for the account view, call it something like "/path/to/api/v1/preload_account" and include all the necessary data. – animatedgif Sep 03 '14 at 19:13