我正在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,}]
1条答案
按热度按时间nhaq1z211#
你说的是api,因此你
Campaign.get_your_campaigns
方法返回一个Hash
看起来是这样的:你可以用
Hash#slice
仅提取您感兴趣的属性。然后将这些属性一个接一个地传递给create方法:注意:您很可能需要为此添加一些错误处理,例如,处理从api返回的无效数据或已导入的句柄记录以避免重复。