如果我指定 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
关于ruby-on-rails - 如何将 ActiveModel::Serializer 应用于自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30049674/