如果我指定ActiveModel对象的简单数组,则序列化程序可以工作:
format.json { render json: @childs, each_serializer: ItemSerializer }
但是我需要使用JSON等其他字段来响应parent_id
。
{parent_id: 15, childs: @childs}
知道如何实现吗?
item_serializer.rb
class ItemSerializer < ActiveModel::Serializer
attributes :id, :name, :parent_id
end
items_controller.rb
def roots
@childs = Item.where(parent_id: 15)
respond_to do |format|
# serializer below does not work...
format.json { render json: {parent_id: 15, childs: @childs}, each_serializer: ItemSerializer }
end
end
耶!我知道了!希望它对别人有帮助!
respond_to do |format|
format.json { render json:
{ parent_id: parent_id, childs: ActiveModel::ArraySerializer.new(@childs, each_serializer: ItemSerializer) }
}
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句