to_json and Rails 2
Published by Andre February 13th, 2008 in Fixes, JavaScript, Ruby on Rails, The BookRails 2 changed the way to_json works on ActiveRecord objects. Prior to Rails 2, to_json returned a hash of hashes — the first level hash had the key ‘attributes’, which in turn had another hash with your field name/values.
With Rails 2, calling to_json on an AR object just gives you a hash of field name/values. The new way is easier and more intuitive. However, in breaks our code in places where we use to_json to pass AR data into JavaScript.
The changes are straightforward. There were two ways we dealt with the intermediate “attributes” hash prior to Rails 2:
- we used map/collect before calling to_json, i.e.: cities.collect{|c|c.attributes}.to_json
- we dealt with ‘attributes’ in JavaScript, i.e., var marker=markers[i].attributes
Fixing it just means removing references to the ‘attributes’ and using the ActiveRecord instance directly.
Here are all the places changes need to be made:
- 3.8: var marker=markers[i].attributes to var marker=markers[i]
- 4.6: all instances of result.attributes to just result
- 4.15: var stores=<%=(@stores.collect {|s|s.attributes}).to_json%>; to var stores=<%=@stores.to_json%>;
- 5-12: remove the to_json method from class Tower
- 7-2: render :text=>cities.collect{|c|c.attributes}.to_json to render :text=>cities.to_json
- 7-5: render :text=>cities.collect{|c|c.attributes}.to_json to render :text=>cities.to_json
- 7.15: var points=<%=@towers.collect{|c|c.attributes}.to_json %>; to var points=<%=@towers.to_json %>;


Get emailed automatically
I use json and have no problem! This is very good think =)
In Rails 2.1, to_json seems to return hash of hashes by default.
# Include Active Record class name as root for JSON serialized output.
# ActiveRecord::Base.include_root_in_json = true