J'utilise will_paginate
et api-pagination
pour paginer mes données et active_model_serializers
pour la sérialisation JSON. Je veux envoyer le total des entrées de la ressource au client où j'utilise AngularJS.Rails 5 - Comment obtenir des entrées totales en utilisant will_paginate et Active Model Serializers
Code contrôleur
def index
comp_id = params[:company_id]
cat_id = params[:category_id]
if comp_id
if comp_id && cat_id
product = Product.where(:company_id => comp_id, :category_id => cat_id)
else
product = Product.where(:company_id => comp_id)
end
paginate json: product,meta: pagination_dict(product), status: 200
else
render json: { errors: "Company ID is NULL" }, status: 422
end
end
sérialiseur
class ProductSerializer < ActiveModel::Serializer
attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished
has_one :category
end
Comment puis-je inclure le TOTAL_COUNT dans ma réponse?
Mise à jour
J'ai essayé d'ajouter la méthode suivante dans mon contrôleur de base selon this doc, mais je reçois une erreur de méthode non définie pour toutes les méthodes définies.
class ApplicationController < ActionController::Base
include Authenticable
include Rails::Pagination
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
protect_from_forgery with: :null_session
def render_404
render json: { errors: 'The requested resource cannot be found' }, status: 404
end
def pagination_dict(collection)
{
#current_page: collection.current_page,
#next_page: collection.next_page,
#prev_page: collection.prev_page, # use collection.previous_page when using will_paginate
total_pages: collection.total_pages,
total_count: collection.total_count
}
end
end