所以我想使用最近添加到 Rails 的新 [ActiveModel::Serializer][1]
。
如果我像这样编写序列化器:
class PatientSerializer < ActiveModel::Serializer
attributes :patient_money, :doctor_name
def doctor_name
object.doctor.name
end
end
我得到的JSON是这样的:
[
// HERE....
{
"patient_money":"40.0",
"doctor_name":"Ostad"
},
{
"patient_money":"30.0",
"doctor_name":"Oz"
},
{
"patient_money":"20.0",
"doctor_name":"Phil"
}
]
这非常接近我想要的,但是在我上面放置“HERE
”注释的地方,我想要一个 JSON 包装层,所以我可以说例如 my_results
然后将这三个 JSON 结果像数组一样包裹在它周围,就像我们在 JBuilder 中创建一个新元素时说 json.my_results
最佳答案
好的,我明白了。
在发送 respond_with(@blah)
的 Controller 中,我应该传递一个根元素并将其命名为我喜欢的任何名称,例如:
respond_with(@blah, root: 'my_results')
关于ruby-on-rails-3.2 - 自定义序列化器的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15376701/