2

I have access to a JSON API and would like to map the API to some classes in my Rails 3.2.1 model, thus I don't need any datatabse.

Example : The API returns the current user with the following JSON {"first_name":"John","last_name":"Smith"}

I'd like to create a new User from that JSON. I read that I can use Active Model.

Basically I'd like to do :

user = User.new.from_json '{"first_name":"John","last_name":"Smith"}'
Rails.logger.debug user.attributes[:first_name]
Rails.logger.debug user.attributes['first_name']
Rails.logger.debug user.first_name

It should print "John" three times.

I use this class

class User
  include ActiveModel::Serializers::JSON
  attr_accessor :attributes
end

but it does not work at all. If I do a user.to_yaml, it returns

--- !ruby/object:User
attributes: John

Any idea ?

Thanks

Geoffroy

shingara
  • 46,608
  • 11
  • 99
  • 105
geoffroy
  • 575
  • 6
  • 18

1 Answers1

2

Try out the following,

user = User.new.from_json('{"first_name":"John","last_name":"Smith"}', false)

If that didn't solve your problem, following should, because internally from_json method uses ActiveSupport::JSON.decode

User.new(ActiveSupport::JSON.decode('{"first_name":"John","last_name":"Smith"}'))
nkm
  • 5,844
  • 2
  • 24
  • 38
  • Many thanks! user = User.new.from_json('{"first_name":"John","last_name":"Smith"}', false) does the trick. The only problem I have is Rails.logger.debug user.first_name fails : NoMethodError (undefined method `first_name' for #) – geoffroy Feb 21 '12 at 14:52
  • It seems like something wrong with the accesser method for first_name attribute in your user class. – nkm Feb 21 '12 at 16:24