在我的控制器中我有:
@photo = Photo.find(:all)
respond_to do |format|
...
format.json { render :json => @photo.to_json)
end
所以我的回答如下:
{
"photo":
{
"updated_at":"2010-10-14T19:12:35Z",
"photo_file_size":206422,
"created_at":"2010-10-14T19:12:01Z"
}
},
{
"photo":
{
"updated_at":"2010-10-16T18:19:38Z",
"photo_file_size":83593,
"created_at":"2010-10-14T19:14:35Z"
}
}
如何为每个照片块添加额外的json键值对? 类似的东西:
"photo":
{
"updated_at":"2010-10-14T19:12:35Z",
"photo_file_size":206422,
"created_at":"2010-10-14T19:12:01Z"
----> "created_at_b":"2010/10/14"
}
也许是:include
选项?
谢谢!
答案 0 :(得分:2)
to_json包含模型上可用的任何方法的结果。例如,您可以将以下方法添加到模型中:
class Photo < ActiveRecord::Base
def created_at_b
# whatever you want to do
end
end
在控制器中添加:
format.json { render :json => @photo.to_json(:methods=>[:created_at_b])
那应该返回你所追求的json。