[英]How to apply ActiveModel::Serializer to a custom object?
If I specify simple array of ActiveModel objects serializer works: 如果我指定ActiveModel对象的简单数组,则序列化程序可以工作:
format.json { render json: @childs, each_serializer: ItemSerializer }
But I need to respond with JSON with additional fields, such as parent_id
, etc. 但是我需要使用其他字段(例如
parent_id
等)来响应JSON。
{parent_id: 15, childs: @childs}
Any idea how to achieve it? 知道如何实现吗?
item_serializer.rb item_serializer.rb
class ItemSerializer < ActiveModel::Serializer
attributes :id, :name, :parent_id
end
items_controller.rb 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
Yay! 好极了! I figure it out!
我知道了! Hope it helps someone else!
希望它能帮助别人!
respond_to do |format|
format.json { render json:
{ parent_id: parent_id, childs: ActiveModel::ArraySerializer.new(@childs, each_serializer: ItemSerializer) }
}
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.