我可以访问JSON API,并希望将API映射到我的Rails 3.2.1模型中的某些类,因此我不需要任何数据表。
示例: API使用以下JSON返回当前用户 { “first_name的”: “约翰”, “姓氏”: “史密斯”}
我想从该JSON创建一个新用户。 我读到我可以使用Active Model。
基本上我想做:
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
它应该打印“John”三次。
我使用这个类
class User
include ActiveModel::Serializers::JSON
attr_accessor :attributes
end
但它根本不起作用。 如果我执行user.to_yaml,则返回
--- !ruby/object:User
attributes: John
有什么想法吗?
由于
弗鲁瓦
答案 0 :(得分:2)
试试以下内容,
user = User.new.from_json('{"first_name":"John","last_name":"Smith"}', false)
如果这没有解决您的问题,请执行以下操作,因为内部from_json
方法使用ActiveSupport::JSON.decode
User.new(ActiveSupport::JSON.decode('{"first_name":"John","last_name":"Smith"}'))