Rails Json response help
In my controller i have:
@photo = Photo.find(:开发者_开发百科all)
respond_to do |format|
...
format.json { render :json => @photo.to_json)
end
so my response looks like:
{
"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"
}
}
how can i add an additional json key value pair for every photo block? something like:
"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"
}
maybe :include
option?
thanks!
to_json can be made to include the result of any method available on your model. For example you could add the following method to your model:
class Photo < ActiveRecord::Base
def created_at_b
# whatever you want to do
end
end
In your controller you add:
format.json { render :json => @photo.to_json(:methods=>[:created_at_b])
That should return the json that you're after.
精彩评论