Forum: Ruby on Rails json formatting

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B455036ffc83a268f77a7561f20a7ab6?d=identicon&s=25 Lyn Williams (lyntaff)
on 2009-05-06 16:14
(Received via mailing list)
I'm really new to rendering formats with rails and would appreciate a
little help with a json issue.

I have created a booking model in which I would like to sync with a
jquery calendar called "full calendar" through json. They have an
example json script output with the following:

[
   {
      "id":1,
      "title":"Event1",
      "start":"2009-05-10",
   },
   {
      "id":2,
      "title":"Event2",
      "start":"2009-05-20",
      "end":"2009-05-22",
      "url":"http:\/\/yahoo.com\/"
   }
]

When using the json format in rails I get:

[
   {
      "booking":{
         "updated_at":"2009-05-01T15:42:44Z",
         "title":"Booking",
         "property_id":1,
         "id":1,
         "end":"2009-05-19",
         "start":"2009-05-06",
         "created_at":"2009-05-01T15:42:44Z"
      }
   },
   {
      "booking":{
         "updated_at":"2009-05-06T09:09:48Z",
         "title":"Booking",
         "property_id":1,
         "id":2,
         "end":"2009-08-26",
         "start":"2009-08-19",
         "created_at":"2009-05-06T09:09:48Z"
      }
   }
]

How do I change how the json format is rendered within rails 2. I need
to get rid of "booking", "updated_at", property_id" and created_at".

Thanks for any help.
3d33a37551176d96ec270d4e4d6c843b?d=identicon&s=25 Keith Litwin (keith74)
on 2009-05-06 21:54
(Received via mailing list)
I think you can do something like this...

@booking.to_json(:only=>["title","id","start","end","url"])
Da55727b189e6a3ddee2ec69f68e0ffb?d=identicon&s=25 Sj Tib (sktib)
on 2009-05-06 22:14
You can avoid getting the table name - which I take it is "booking" in
your case - by telling ActiveRecord not to include that with the
following code

ActiveRecord::Base.include_root_in_json = false

You can filter the fields you want in your database query and then
to_json on the query result should give you what you need without the
table name.

-S
0c31801aba0747b84974df56ade208f3?d=identicon&s=25 Quy Doan (doantranquy)
on 2009-05-08 00:24
(Received via mailing list)
you can use except option in to_json
Example :
  @booking.to_json(:except=>[:updated_at,:property_id,:created_at]
and to get rid of booking. From rails 2.1+ you should configure in
config/initializers/new_rails_defaults.rb file  :
  ActiveRecord::Base.include_root_in_json = false
This topic is locked and can not be replied to.