2017-07-30 68 views
1

我正在使用will_paginateapi-pagination來爲我的數據分頁,並且使用active_model_serializers來進行JSON序列化。 我想將資源的全部條目發送到我使用AngularJS的客戶端。Rails 5 - 如何使用will_paginate和活動模型序列化程序獲取總條目

控制器代碼

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 

串行

class ProductSerializer < ActiveModel::Serializer 
    attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished 
    has_one :category 
end 

我怎麼能包括我的迴應的TOTAL_COUNT?

更新

我嘗試添加下面的方法在我的基本控制器按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 
相關問題