views:

2372

answers:

4

I have some existing projects that were built upon a deprecated PHP framework, and I'm hoping to move them over to Ruby on Rails with minimal effort. My main problem right now is the format that the JSON is coming back in. My frontend code (all ExtJS) is expecting JSON in the format:

{
    "result": [
        [id: 1, name: "mike"],
        [id: 2, name: "john"],
        [id: 3, name: "gary"]
    ]
}

But the default return from Ruby on Rails is as follows:

{
    "result": [
        {"record" : {id: 1, name: "mike"}},
        {"record" : {id: 2, name: "john"}},
        {"record" : {id: 3, name: "gary"}}
    ]
}

My controller is basically doing nothing but:

@records = Record.find(:all)
respond_to do |format|
  format.json { render :text => @records.to_json}
end

As you can see, it's adding in an additional key to every record, which my frontend ExtJS code is not capable of parsing as-is. Is there any way to stop this from occuring?

Thanks for any help you can offer,

Mike Trpcic

+2  A: 

This question can now be closed, but I feel it relevant that I post the solution for anyone in the future who runs into the same situation. You can use the following plugin: Ext Scaffold Generator. even if you don't wish to use the scaffold functionality, it adds an additional "to_ext_json" method that outputs JSON that is readable by ExtJS by default.

Thanks to anyone who looked into the matter and tried to help me.

Mike Trpcic
+1  A: 

You could also try:

@records = Record.find(:all)
respond_to do |format|
  format.json { render :json => @records.map {|r| r.attributes } }
end
Yehuda Katz
+2  A: 

Here's a pattern that works for me:

format.json { render :json =>  {
          :rows => @data_array,
          :results => @data_array.length
        }, :callback => params[:callback]}

HTH

Allan
+2  A: 

basically :

ActiveRecord::Base.include_root_in_json = false

or

YourClass.include_root_in_json = false

as described here: http://apidock.com/rails/ActiveRecord/Serialization/to_json

airy