使用Rails 4.1.6和active_model_serializers 0.10.3
应用程序/串行器/ product_serializer.rb
class ProductSerializer < ActiveModel::Serializer
attributes :id, :title, :price, :published
has_one :user
end
应用程序/控制器/ API / V1 / products_controller.rb
class Api::V1::ProductsController < ApplicationController
respond_to :json
def index
products = Product.search(params).page(params[:page]).per(params[:per_page])
render json: products, meta: pagination(products, params[:per_page])
end
end
当我检查响应正文时,它仅显示产品数据:
[{:id=>1, :title=>"Side Auto Viewer", :price=>"1.6999510872877", :published=>false, :user=>{:id=>2, :email=>"indira.sawayn@watsica.us", :created_at=>"2016-12-29T03:44:40.450Z", :updated_at=>"2016-12-29T03
:44:40.450Z", :auth_token=>"ht7CsFWM1hvSGKM_zPmU"}}, {:id=>2, :title=>"Direct Gel Mount", :price=>"56.7935950121941", :published=>false, :user=>{:id=>3, :email=>"jaye.rolfson@leuschke.info", :created_at=>
"2016-12-29T03:44:40.467Z", :updated_at=>"2016-12-29T03:44:40.467Z", :auth_token=>"MTK_5rkFv8E6Fy7gyAtM"}}, {:id=>3, :title=>"Electric Tag Kit", :price=>"46.4689779902597", :published=>false, :user=>{:id=
>4, :email=>"tatiana@moen.co.uk", :created_at=>"2016-12-29T03:44:40.479Z", :updated_at=>"2016-12-29T03:44:40.479Z", :auth_token=>"fTd8z7PCLHxZ7aewLPDY"}}, {:id=>4, :title=>"Remote Tuner", :price=>"48.2478
906626996", :published=>false, :user=>{:id=>5, :email=>"pauline.gaylord@hettinger.info", :created_at=>"2016-12-29T03:44:40.486Z", :updated_at=>"2016-12-29T03:44:40.486Z", :auth_token=>"XC7ZhcyfPrpEyDw-M15
1"}}]
未提取额外数据meta
。这个active_model_serializers
版本不支持吗?或者有办法获得额外的数据吗?
pagination
方法:
def pagination(paginated_array, per_page)
{ pagination: { per_page: per_page.to_i,
total_pages: paginated_array.total_pages,
total_objects: paginated_array.total_count } }
end
答案 0 :(得分:2)
我遇到了同样的问题,通过指定要在render方法调用中使用的适配器来修复它:
app/controllers/api/v1/products_controller.rb
class Api::V1::ProductsController < ApplicationController
respond_to :json
def index
products = Product.search(params).page(params[:page]).per(params[:per_page])
render json: products, meta: pagination(products, params[:per_page]), adapter: :json
end
end