Ruby on Rails parse api to save to db - ruby-on-rails

I am practicing with apis in RoR. I am trying to save only a few items from the api call id, length, dip, name but how do I parse it and save the fields that I need and do they need to be in params? Currently the api call data is not in params.
On button click I want to have those fields listed above save into the db
routes
root 'welcome#index'
post 'search_campaigns', to: 'campaigns#search_all_campaigns'
my model
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
controller
class CampaignsController < ApplicationController
def search_all_campaigns
#campaigns = Campaign.get_your_campaigns
redirect_to root_path
end
end
view
<%= button_to 'Get All Campaigns', search_campaigns_path %>
This how the api call data looks
[{"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,}]

You say the API and therefore you Campaign.get_your_campaigns method returns a Hashthat looks like this:
[
{
"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,
}
]
You can use Hash#slice to extract only the attributes you are interested in. And then pass those attributes one after the other to the create method:
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) }
Note: You will very likely need to add some error handling to this, for example, to deal with invalid data returned from the API or the handle records that have already been imported to avoid duplicates.

Related

Rails why isn't my api json format not showing up in the params hash?

I am practicing with apis in RoR. The user clicks on a link on the root page and it does a Get call to the api and saves all the fields that I want to the db. But when I look at the params hash it is empty? Why is that and how would I go about adding to the params hash the JSON data?
controller
class CampaignsController < ApplicationController
def index
end
def save_your_campaigns
campaigns = Campaign.get_your_campaigns
campaigns_attributes = JSON::parse(campaigns)
campaigns_attributes.each {|attribute| Campaign.create(campaign_id: attribute["id"], name: attribute["name"], dpi: attribute["dpi"], length: attribute["length"] )}
redirect_to root_path
end
end
model
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 response.body
end
end
view
<h1>Welcome!<h1>
<%= link_to 'Get All Campaigns', save_campaigns_path %>
JSON data
[
{
"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,
}
]

Error SENDING POST in rails and HTTPPARTY semantic error my request

this is my error when I lanunched my method {"errors"=>{"users"=>["Missing data for required field."]}, "msg"=>"The request was well-formed but was unable to be followed due to semantic errors."}
class BookingNotifier
include HTTParty
def initialize(booking_id)
#booking = Booking.find booking_id
#venue = #booking.event.service.venue
#body = { "users" => [] }
#headers = {
"Accept" => "application/json",
"Authorization" => "ENV_KEY",
"Content-Type" => "application/json"
}
end
def send_venue_notification
venues_objects = []
if #venue.notifications_enabled
venues_objects << { "cellphone" => #booking.event.service.venue.phone,
"country_code" => "+57",
"user_session_keys" => [{ "key" => "Nombre", "value" => #booking.profile.name },
{ "key" => "Centro", "value" => #booking.event.service.venue.name },
{ "key" => "Cupos", "value" => #booking.quantity },
{ "key" => "Horarios", "value" => #booking.time.strftime("%I:%M %p el %d/%m/%Y") }] }.to_json
#body["users"] = venues_objects
make_request_venue
end
end
def make_request_venue
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #header, body: #body)
end
The problem is caused by to_json called in the wrong place.
The whole request body should be sent as a JSON. In your code, you call to_json for a hash that is later pushed into #body["users"] array.
Please remove to_json from send_venue_notification and call it for the #body when sending the request:
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #headers, body: #body.to_json)

add two parameters in Soulmate::Loader

i have two fields in my model and i want add them in Soulmate::Loader:
for example, my "person" model has name and email field. and i want load then in Soulmate:
loader = Soulmate::Loader.new("people")
loader.add("term" => name, "id" => self.id, "data" => {
"link" => Rails.application.routes.url_helpers.person_path(self)
})
i want add name and email in loader.add. but i can't.
def load_into_soulmate
loader = Soulmate::Loader.new("people")
loader.add("term" =>{ name , email }, "id" => self.id, "data" => {
"link" => Rails.application.routes.url_helpers.person_path(self)
})
end
and
def load_into_soulmate
loader = Soulmate::Loader.new("people")
loader.add("term" =>{ "name" => name ,"email" => email }, "id" => self.id, "data" => {
"link" => Rails.application.routes.url_helpers.person_path(self)
})
end
error show when i use Person.find_each(&:save) for add datas to redis:
ArgumentError: ArgumentError
from /var/lib/gems/2.2.0/gems/soulmate-1.1.0/lib/soulmate/loader.rb:31:in `add'
but all is wrong.
I think you have to use aliases.
def load_into_soulmate
loader = Soulmate::Loader.new("people")
loader.add("term" =>"name", "id" => self.id, "aliases" => [email], "data" => {
"link" => Rails.application.routes.url_helpers.person_path(self)
})
end

Invalid authorization name/value {x-li-auth-token}/{NAME_SEARCH:tdLy}

Im working on LinkedIn invitation API but I can't send the invitation to user, using people id from search result
Seached people result
**
"{\"people\":{\"total\":2,\"all\":[{\"api_standard_profile_request\":{\"headers\":{\"total\":1,\"all\":[{\"name\":\"x-li-auth-token\",\"value\":\"NAME_SEARCH:tdLy\"}]},\"url\":\"http://api.linkedin.com/v1/people/tp2Z82Xa_I\"},\"first_name\":\"Dev\",\"id\":\"tp2Z8sad2Xa_I\",\"last_name\":\"ruby\"},{\"api_standard_profile_request\":{\"headers\":{\"total\":1,\"all\":[{\"name\":\"x-li-auth-token\",\"value\":\"NAME_SEARCH:ZbY6\"}]},\"url\":\"http://api.linkedin.com/v1/people/TyaEtFbxzL\"},\"first_name\":\"dev\",\"id\":\"TyaEtFbsdsaxzL\",\"last_name\":\"ruby\"}]}}"**
And the invite methods following this
def send_invitation(options)
path = "/people/~/mailbox"
message = {
"recipients" => {
"values" => [
{
"person" => {
"_path" => "/people/id=#{options[:email]}",
"first-name" => options[:first_name],
"last-name" => options[:last_name]
}
}]
},
"subject" => "Invitation to connect.",
"body" => options[:body],
"item-content" => {
"invitation-request" => {
"connect-type" => "friend",
"authorization" => {"name" => "x-li-auth-token","value" => "NAME_SEARCH:tdLy"}
}
}
}
post(path, MultiJson.dump(message), "Content-Type" => "application/json")
end
So I am getting this error when I call client.send_invitation(options):
LinkedIn::Errors::GeneralError: (400): Invalid authorization name/value {x-li-auth-token}/{NAME_SEARCH:tdLy}
Working Fine
The name should be NAME_SEARCH and the value should be tdLy instead of what i have asked above. i have to split the value out of the oauth headers.
"authorization" => {:"name" => 'NAME_SEARCH',:"value" => 'tdLy'}

json format from rails to sproutcore

For those of you using Rails as a backend to their Sproutcore clients,
which one is the best way to format the data into json?
From the Sproutcore guides there was this approach:
def as_json(options = {})
event_hash = {
"guid" => self.id,
"id" => self.id,
"designation" => self.designation,
"category" => self.category,
"scheduled_for" => self.scheduled_for,
"location" => self.location,
"groups" => self.groups,
"resources" => self.resources
}
event_hash
end
But it fails, send an "Illegal statement error". Then, I changed to this other method:
def as_json(options = {})
# event_hash = options.merge(:include => [:groups, :resources], :methods => :guid)
event_hash = options.merge(:methods => :guid)
super(event_hash)
end
which seems to be working as far as the formatting is concerned, although I am suspecting it to causing some trouble regarding the representation in the dataHash of the store. Anyway, ha anyone been having similar issues with the first version of as_json? If not, is there anything I am doing wrong?
Appreciate any help
On the first method you need to call super:
def as_json(options = {})
event_hash = {
"guid" => self.id,
"id" => self.id,
"designation" => self.designation,
"category" => self.category,
"scheduled_for" => self.scheduled_for,
"location" => self.location,
"groups" => self.groups,
"resources" => self.resources
}
super(event_hash)
end
However you should get the options param and process to do this apropiately.

Resources