geoffroy
geoffroy

Reputation: 585

Mapping a JSON Api to a Model in Rails

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

Upvotes: 2

Views: 2446

Answers (1)

nkm
nkm

Reputation: 5914

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"}'))

Upvotes: 2

Related Questions