views:

23

answers:

1

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!

+2  A: 

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.

NZKoz
How can i add in every photo the "created_at_b" field?
vic
That's what the first block of code is for, you'd put that method definition in your model class. I've edited the answer so it's a bit more clear
NZKoz