ActiveModelSerializers

Cześć,

Używam “active_model_serializers” ver 0.9.3

Gdy robię:

respond_to do |format|
  format.json { 
    render json: @customers_on_page, each_serializer: CustomerSerializer, meta: @customers.count  
    }
end

czyli stosuję “magiczne” “meta:” to dostaję:

  {
    customers: [],
    meta: 68004
  }

Chciałbym jednak aby zamiast

meta: 68004

było w tym JSONie

total_count: 68004

Jak należy użyć meta_key (lub może inaczej jeszcze coś zrobić), by osiągnąć zamierzony efekt?

A…
Deklaracja:

render json: @customers_on_page, each_serializer: CustomerSerializer, total_count: @customers.count  

zwraca

  {
    customers: []
  }
render json: @customers_on_page, each_serializer: CustomerSerializer, meta: @customers.count, meta_key: 'total_count'
1 Like

Przykład taki jest w dokumentacji:

If you want a meta attribute in your response, specify it in the render call:

render json: @post, meta: { total: 10 }

The key can be customized using meta_key option.

render json: @post, meta: { total: 10 }, meta_key: "custom_meta"

meta will only be included in your response if you are using an Adapter that supports root, as JsonAPI and Json adapters, the default adapter (Attributes) doesn’t have root.

…ale mi nie działa i dostaję samo:

  {
    customers: []
  }

! :frowning:

Stąd właśnie moja prośba do Was o pomoc.

A co masz w CustomerSerializer?

class CustomerSerializer < ActiveModel::Serializer
  #attributes *Customer.column_names
  attributes :id, :name, :given_names, :fullname  

  def fullname
    "#{object.name} #{object.given_names}"
  end

end

Ktoś wpadł na pomysł, co może być przyczyną mojego problemu? :frowning: