我正在使用ruby on rails进行API。我有两个方法在json中返回资源。这两种资源彼此之间没有任何关系。我想要做的是构建一个方法,在一个请求中返回这两个资源。在不损害宁静原则的情况下,最好的方法是什么?我应该保持这种方式吗?
修改
我的档案可以更好地解释自己。
的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
我应该创建第三个控制器并路由以在一个JSON中将这两个资源放在一起吗?那是更好的方式吗?
答案 0 :(得分:0)
假设这两个资源应该在同一个请求中出现是有充分理由的,你可以用这样的格式呈现它们:
{
"rabbit" => { ... },
"mouse" => { ... }
}