method

from_json

Importance_1
Ruby on Rails latest stable (v7.1.3.2) - 2 notes - Class: ActiveRecord::Serialization

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

These similar methods exist in v7.1.3.2:

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:

User.new.from_json '{"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
konata.to_json
=> { "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.new.from_json(konata.to_json[“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.