2017-07-30 11 views
1

私はwill_paginateapi-paginationを使用してデータをページ付けし、active_model_serializersをJSONのシリアル化に使用しています。 AngularJSを使用しているクライアントにリソースの合計エントリを送信したいと思います。Rails 5 - will_paginateとActive Modelシリアライザを使用して合計エントリを取得する方法

コントローラーコード

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 

シリアライザ

私は私の応答にTOTAL_COUNTを含めることができますどのように
class ProductSerializer < ActiveModel::Serializer 
    attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished 
    has_one :category 
end 

更新

しかし私は、私が定義されているすべてのメソッドのための未定義のメソッドのエラーを取得しています、thisドキュメントごとに私のベースコントローラで次のメソッドを追加してみました。

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 

答えて

0

これらのメソッド(total_pagestotal_entriesは...)paginated ActiveRecordの関係でのみ動作します。

たとえば、Product.where(company_id: comp_id).page(1).total_pagesは、リレーションがpaginationを使用するため、合計ページ数を返します。

あなたの場合、ActiveRecordのcountメソッドを使用して総エントリ数を取得するだけではどうですか?

paginate json: product, meta: product.count, status: 200 
関連する問題