Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render json with extra data with active_model_serializer on rails?

Using Rails 4.1.6 and active_model_serializers 0.10.3

app/serializers/product_serializer.rb

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :title, :price, :published
  has_one :user
end

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])
  end
end

When I check the response body, it shows the products data only:

[{:id=>1, :title=>"Side Auto Viewer", :price=>"1.6999510872877", :published=>false, :user=>{:id=>2, :email=>"[email protected]", :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=>"[email protected]", :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=>"[email protected]", :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=>"[email protected]", :created_at=>"2016-12-29T03:44:40.486Z", :updated_at=>"2016-12-29T03:44:40.486Z", :auth_token=>"XC7ZhcyfPrpEyDw-M15
1"}}]

The extra data meta was not been picked up. Is this active_model_serializers version not support that? Or is there a way can get extra data?


Edit

The pagination method:

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
like image 635
Jingqiang Zhang Avatar asked Feb 06 '23 10:02

Jingqiang Zhang


1 Answers

I had the same issue, and it's been fixed by specifying the adapter to use in the call to render method:

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
like image 98
Pierre Michard Avatar answered Feb 15 '23 23:02

Pierre Michard