成员-数据似乎希望一个假设的颜色模型的数据数组看起来如下:
{
"colors": [{
name: "red"
}, {
name: "blue"
}, {
name: "green"
}]
}也就是说,它需要一个根元素,它是您的模型的任何类型的复数。我想知道如何让rails以这种方式使用active_model_serializers gem发送JSON。以下是我所拥有的:
# GET /colors
# GET /colors.json
def index
@colors = Color.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @colors, :root => 'colors' }
end
end但这就产生了:
{
colors: [
{
colors: {
name: "red"
}
}, {
colors: {
name: "blue"
}
}, {
colors: {
name: "green"
}
}
}]
}也就是说,数组和每个对象上都有一个根元素。我只想把它放在数组上。任何帮助都是非常感谢的。谢谢!
发布于 2014-01-24 01:07:07
我最终通过添加我自己的自定义序列化程序来解决这个问题。
app/序列化器/color_序列化器.app
class ColorSerializer < ActiveModel::Serializer
attributes :name
self.root = false
end然后用
render json: @colors, each_serializer: ColorSerializer它在保留数组中的根元素的同时禁用了每个对象根元素。
https://stackoverflow.com/questions/21298456
复制相似问题