0

シリアライザを別のシリアライザで使用したいので、トップレベルでキーと値のペアを追加できますが、 anymore-Railsネストされたシリアライザはキーを抜けるメソッドを使用していません

マイファイル:

ItemsController

class ItemsController 

    def index 
    open_items = Items. 
     select("distinct on (open_item_id) *"). 
     preload(:company, :project) 

    total = open_items.count("id") 

    render json: { 
     total: total, 
     items: paginate(open_items, per_page: 2), serializer: ItemsSerializer 
    }, status: :ok 
    end 
end 

ItemsSerializer

class ItemsSerializer < ActiveModel::Serializer 
    attribute :total 
    has_many :items, serializer: ItemSerializer 
end 

ItemSerializer

クラスItemSerializer < ActiveModel ::シリアライザ 属性:id、 :プロジェクト、 :会社、

def company 
    { 
     name: object.company.name, 
     id: object.company.id 
    } 
    end 

    def project 
    { 
     name: object.project.name, 
     id: object.project.id 
    } 
    end 

end 

は、私は別のキー/値のペアを取得したいです私のシリアライザの出力には以下のようになります。

{ 
    "total": 1, 
    "items": [ 
     { 
      "id": 42920375, 
      "company": { 
      "id": 123, 
      "name": "CompanyName" 
      }, 
      "project": { 
      "id": 456, 
      "name": "ProjectName" 
      } 
     } 
    ] 
} 

しかし、現在、私が取得しています:

{ 
    "total": 1, 
    "items": [ 
     { 
      "id": 42920375, 
      "company_id": 5842, 
      "project_id": 191741, 
     } 
    ] 
} 
+1

私は問題は 'ItemsSerializer'があなたが望むように動作しないと思います。アクティブなモデル名に対応する必要があります。あなたが持っているのは、ActiveRecord独自の 'to_json'メソッドの結果です。 – EJ2015

答えて

0

私はあなたがそのようItemsSerializer使用することができないと思います。それはモデルに対応する必要があります。

アクティブモデルシリアライザは自動的に独自のシリアライザに関連して、各オブジェクトをシリアル化します:

"In your controllers, when you use render :json for an array of objects, AMS will use ActiveModel::ArraySerializer (included in this project) as the base serializer, and the individual Serializer for the objects contained in that array."

だから、車輪を再発明する必要はありません。これを行うだけです:

render json: paginate(open_items, per_page: 2), status: :ok 

各項目はItemSerializerで処理されます。私はここにtotalを加える方法を見ない。

関連する問題