RubyonRails解析api以保存到db

hi3rlvi2  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(225)

我正在ror中练习API。我试图只保存api调用中的一些项 id, length, dip, name 但是我如何解析它并保存我需要的字段,它们是否需要在params中?当前api调用数据不在参数中。
单击按钮,我想将上面列出的字段保存到数据库中
路线

root 'welcome#index'
  post 'search_campaigns', to: 'campaigns#search_all_campaigns'

我的模型

class Campaign < ApplicationRecord
  def self.get_your_campaigns
    uri = URI.parse("https://example.site/api/v2/users")
    request = Net::HTTP::Get.new(uri)
    request.content_type = "application/json"
    request.basic_auth("example@email.com", "238urfs393kmdsb2189aead01")
    req_options = {
      use_ssl: uri.scheme == "https",
    }
    response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
      http.request(request)
    end
    return JSON.parse(response.body)
  end
end

控制器

class CampaignsController < ApplicationController

  def search_all_campaigns
    @campaigns = Campaign.get_your_campaigns
    redirect_to root_path
  end
end

看法

<%= button_to 'Get All Campaigns', search_campaigns_path %>

这是api调用数据的外观

[{"id"=>2758, "dip"=>"2.0", "length"=>10, "name"=>"Cereal", "total_remaining"=>100, "status"=>6, "is_retarget"=>false}, {"id"=>278563, "dip"=>"1.25", "length"=>2, "name"=>"Pizza", "total_remaining"=>123, "status"=>6, "supplier_link"=>"http://www.developingmedia.com/adhoc.php?id=", "incidence"=>50, , "days_in_field"=>5, "max_daily_completes"=>nil, "is_retarget"=>false}, {"id"=>278564, "dip"=>"4.25", "length"=>25, "name"=>"California", "days_in_field"=>5,}]
nhaq1z21

nhaq1z211#

你说的是api,因此你 Campaign.get_your_campaigns 方法返回一个 Hash 看起来是这样的:

[
  {
    "id" => 2758, 
    "dip" => "2.0", 
    "length" => 10, 
    "name" => "Cereal", 
    "total_remaining" => 100, 
    "status" => 6, 
    "is_retarget" => false
  }, 
  {
    "id" => 278563, 
    "dip" => "1.25", 
    "length" => 2, 
    "name" => "Pizza", 
    "total_remaining" => 123, 
    "status" => 6, 
    "supplier_link" => "http://www.developingmedia.com/adhoc.php?id=", 
    "incidence" => 50, , 
    "days_in_field" => 5, 
    "max_daily_completes" => nil, 
    "is_retarget" => false
  }, 
  { 
    "id" => 278564, 
    "dip" => "4.25", 
    "length" => 25, 
    "name" => "California", 
    "days_in_field" => 5,
  }
]

你可以用 Hash#slice 仅提取您感兴趣的属性。然后将这些属性一个接一个地传递给create方法:

campaigns_hashes = Campaign.get_your_campaigns    
campaigns_attributes = campaigns_hashes.map { |hash| hash.slice(:id, :name, :length, :dip) }
campaigns = campaigns_attributes.each { |attributes| Campaign.create(attributes) }

注意:您很可能需要为此添加一些错误处理,例如,处理从api返回的无效数据或已导入的句柄记录以避免重复。

相关问题