シリアライザを別のシリアライザで使用したいので、トップレベルでキーと値のペアを追加できますが、 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,
}
]
}
私は問題は 'ItemsSerializer'があなたが望むように動作しないと思います。アクティブなモデル名に対応する必要があります。あなたが持っているのは、ActiveRecord独自の 'to_json'メソッドの結果です。 – EJ2015