views:

34

answers:

1

I'm working on a RoR project and I am passing a JSON object to a script. Specifically, a list of events to a jquery calendar.

First I get the necessary events from active record and convert them to json:

@events = CalendarEvent.find(:all, :conditions => ["mentor_id = ?", current_user]).to_json(:only => [:id, :availability, :starts_at, :ends_at])

This returns the following:

[{"calendar_event":{"starts_at":"2010-08-14T17:15:00Z","id":1,"availability":true,"ends_at":"2010-08-14T17:45:00Z"}},
 {"calendar_event":{"starts_at":"2010-08-15T15:45:00Z","id":2,"availability":true,"ends_at":"2010-08-15T16:15:00Z"}},
 ...]

However, I am running into problems because the script is expecting the following format:

[{"starts_at":"2010-08-14T17:15:00Z","id":1,"availability":true,"ends_at":"2010-08-14T17:45:00Z"},
 {"starts_at":"2010-08-15T15:45:00Z","id":2,"availability":true,"ends_at":"2010-08-15T16:15:00Z"},
 ...]

At first I thought it would be a simple matter of popping the values from the separate hashes, and returning an array filled with those. However, it seems that everything in the array is one big string. So I was trying to get the necessary stuff using a regular expression. My best shot was:

@json = @events.scan(/\[\{\"calendar_event\":(\{.*\})\}\]*/)

But this returns something of the form:

[["{\"starts_at\":\"2010-08-14T17:15:00Z\",\"id\":1,\"availability\":true,\"ends_at\":\"2010-08-14T17:45:00Z\"}},{\"calendar_event\":{\"starts_at\":\"2010-08-15T15:45:00Z\",\"id\":2,\"availability\":true,\"ends_at\":\"2010-08-15T16:15:00Z\"}},..."]]

Any help would be appreciated.

+1  A: 
ActiveRecord::Base.include_root_in_json = false

Have fun.

Reading documentation helps.

Tass
Thank you. I wish I had found this a few hours ago.
Phillip