v2.3.8 - Show latest stable - 2 notes - Class: ActiveRecord::Serialization
from_json(json) public

No documentation

This method has no description. You can help the Ruby on Rails community by adding new notes.

Show source
Register or log in to add new notes.
July 24, 2009
1 thank

Instance method

Please note that this is an instance method, not a class method (which seemed more logical for me and took me a while to see what’s wrong). So, you call it like this: '{"id": 1, "name": "DHH"}' # RIGHT!

not like this:

User.from_json '{"id": 1, "name": "DHH"}' # WRONG!
May 4, 2010
0 thanks

Be careful about ActiveRecord::Base.include_root_in_json

If you have set ActiveRecord::Base.include_root_in_json = true, then when you do .to_json on an object, the output will begin with the class name rather than just a hash of attributes.

from the rails docs

konata = User.find(1)
ActiveRecord::Base.include_root_in_json = true
=> { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
          "created_at": "2006/08/01", "awesome": true} }

if you try to pass this output as the argument to from_json, things will blow up.[“user”]) will just pass in the attribute hash and will work.

Also, note that if you’ve use attr_accessible to limit mass assignment, you’ll have problems if you try pass in attributes that are not allowed to be mass assigned.