保存外部JSON到数据库使用Rails [英] Saving external JSON to DB with Rails

查看:183
本文介绍了保存外部JSON到数据库使用Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是创业板httparty一个GET调用外部来源;这里是我的Controller.rb:

 高清节目
  响应= HTTParty.get(URI)
  用户= JSON.parse(响应)
  user.each {|线|放线['用户'] ['身份证']}
  #系统['用户'] ['身份证'],就是因为是后返回的嵌套JSON对象
  解析。
结束

这将返回我的rails控制台正确的输出,但现在的问题是我怎么了['身份证']保存到我的数据库?

目前,我的用户模型有:ID和:名称;从外部API JSON对象发送:ID和:名一堆其他的信息,我不需要一起。

 类用户< ActiveRecord的::基地
   attr_accessor中:ID,:名称
结束

任何帮助是AP preciated,谢谢!


解决方案

首先,我建议你的ID创建另一列(比如 EXTERNAL_ID 或某事),而不是保存在实际 ID 用户的列模型(即列在ActiveRecord的,你真的很重要不希望被直接设置的话)。您可以在该列的唯一性进行验证,以确保您不会在数据库中导入相同的用户数据分成多个单独的记录。

一旦你的专栏,创建你的用户一个类的方法模型(我叫雷 save_data_from_api )的JSON数据加载到数据库:

 类用户< ActiveRecord的::基地  #可选的,但很可能是个好主意
  验证:EXTERNAL_ID,:独特= GT;真正  高清self.save_data_from_api
    响应= HTTParty.get(URI)
    的user_data = JSON.parse(响应)
    用户= user_data.map做|线|
      U = User.new
      u.external_id =行['用户'] ['身份证']
      #设置名称值,但是你想这样做
      u.save
      ü
    结束
    users.select(安培;:坚持?)
  结束结束

它所做的:


  • JS​​ON数据映射到一个块( user_data.map ),这需要每个用户JSON和

    1. 初始化一个新用户( User.new

    2. 分配给它的ID JSON数据(行['用户'] ['身份证']

    3. 保存新用户( u.save )和

    4. 返回其它(最后一个 U 块)。


  • 然后,拍摄效果(分配给用户),并只选择那些实际存在(是坚持)在DB( users.select (安培;:?坚持))。例如,如果您有关于 EXTERNAL_ID 唯一性约束,并尝试再次加载DB数据, u.save 将返回,该记录将不会是(重新)创建的,这些结果将被过滤掉的结果从方法返回。

这可能是也可能不是你想要的返回值。此外,你可能想(从JSON数据名称等)块增加更多的属性分配。我把它留给你填写的其他细节。

I'm making a GET call to an external source using the gem 'httparty'; here's my Controller.rb:

def show
  response = HTTParty.get('URI')
  user = JSON.parse(response)
  user.each {|line| puts line['user']['id']}
  #the "['user']['id']" is because of the nested JSON object that is returned after the 
  parse.
end

This returns the correct output in my rails console, but now the question is how do I save the ['id'] to my db?

Currently, my User model has :id and :name; the JSON object from the external API sends :id and :name along with a bunch of other information I don't need.

class User < ActiveRecord::Base
   attr_accessor :id, :name
end

Any help is appreciated, thanks!

解决方案

First, I would suggest that you create another column for the id (say external_id or something), rather than saving it in the actual id column of the User model (that column is very important in ActiveRecord and you really don't want to be setting it directly). You can validate uniqueness on that column to ensure that you don't import the same user data into multiple separate records in the db.

Once you have that column, create a class method in your User model (I've called mine save_data_from_api) to load the JSON data into the db:

class User < ActiveRecord::Base

  # optional, but probably a good idea
  validates :external_id, :uniqueness => true

  def self.save_data_from_api
    response = HTTParty.get('URI')
    user_data = JSON.parse(response)
    users = user_data.map do |line|
      u = User.new
      u.external_id = line['user']['id']
      # set name value however you want to do that
      u.save
      u
    end
    users.select(&:persisted?)
  end

end

What this does:

  • Map the JSON data to a block (user_data.map) which takes each JSON user and

    1. initializes a new user (User.new)
    2. assigns it the id JSON data (line['user']['id'])
    3. saves the new user (u.save), and
    4. return its it (the last u in the block).

  • Then, take the result (assigned to users) and select only those that actually exist (were persisted) in the db (users.select(&:persisted?)). For example, if you have a uniqueness constraint on external_id and you try to load the db data again, u.save will return false, the record will not be (re-)created, and those results will be filtered out of the results returned from the method.

This may or may not be the return value you want. Also, you probably want to add more attribute assignments (name, etc. from the JSON data) in the block. I leave it up to you to fill in those other details.

这篇关于保存外部JSON到数据库使用Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆