method

from_json

from_json(json)
public

No documentation available.

# File activerecord/lib/active_record/serializers/json_serializer.rb, line 60
    def from_json(json)
      self.attributes = ActiveSupport::JSON.decode(json)
      self
    end

2Notes

Instance method

szeryf · Jul 24, 20091 thank

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!

Be careful about ActiveRecord::Base.include_root_in_json

steven_chanin · May 4, 2010

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.