How to create a HTTP post request using the form fields to the external websites API using Ruby on Rails?

437 Views Asked by At

I am trying to create a HTTP post request using the form fields to the external website here it is factual.com

I have created the method in the my data_controller.rb which is like

def posttofactual

uri = URI.parse("http://api.factual.com/v2/tables/Nj0JN3/input?")

# Full control
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data({"name" => "datum.name", "address" => "datum.address",   "locality" => "datum.locality", "region" => "datum.region", "postcode" => "datum.postcode","category" => "datum.category","website" => "datum.website","latitude" => "datum.latitude","longitude" => "datum.longitude","&APIKey=" => "myapikey" })

# Tweak headers, removing this will default to application/x-www-form-urlencoded
request["Content-Type"] = "application/json"

response = http.request(request)

 end

I have a form like

<%= form_for(@datum) do |f| %>
<% if @datum.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@datum.errors.count, "error") %> prohibited this datum from being saved:</h2>
<ul>
<% @datum.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :address %><br />
<%= f.text_field :address %>
</div>
<div class="field">
<%= f.label :locality %><br />
<%= f.text_field :locality %>
</div>
<div class="field">
<%= f.label :region %><br />
<%= f.text_field :region %>
</div>
<div class="field">
<%= f.label :postcode %><br />
<%= f.number_field :postcode %>
</div>
<div class="field">
<%= f.label :category %><br />
<%= f.text_field :category %>
</div>
<div class="field">
<%= f.label :website %><br />
<%= f.text_field :website %>
</div>
<div class="field">
<%= f.label :latitude %><br />
<%= f.text_field :latitude %>
</div>
<div class="field">
<%= f.label :longitude %><br />
<%= f.text_field :longitude %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>    

I want to call "posttofactual" method on this line <%= f.submit %> on the form field.

1

There are 1 best solutions below

0
Sergio Tulentsev On

It seems like your form will post to either create or update method of the controller. There you should extract data from params and call your posttofactual method.