Morez SA
Morez SA

Reputation: 87

How to automatically save data from API - Ruby on Rails

I have searched all over the internet, however, I cannot seem to get a clear answer on this issue. I am using Block.io API to add Bitcoin payments to my app. I receive a JSON hash which includes a new Bitcoin address for each payment, I can extract the bitcoin address, but I need it to save to my database automatically, when a user accesses a specific page the address will also be generated on that page. I am using Postgresql

The JSON looks like this:

{"status"=>"success", "data"=>{"network"=>"BTCTEST", "address"=>"2MstFNxtnp3pLLuXUK4Gra5dMcaz132d4dt", "available_balance"=>"0.01000000", "pending_received_balance"=>"0.00000000"}}

I have a controller which calls the API to generate the address:

class PaymentsController < ApplicationController
  def index
   @new_address = BlockIo.get_new_address
  end
end

And the bitcoin address is displayed using:

<%= @new_address["data"]["address"] %>

I am thinking of creating a new function that will save the bitcoin address to the database and map the route to execute this function upon accessing the specific page, something like:

Controller:

class PaymentsController < ApplicationController
  def create
   @new_address = BlockIo.get_new_address

 ## I need assistance with the rest to auto save

  end
end

routes:

match '/save_btc' => 'payments#create', via: [:get, :post]

when someone opens domain.com/save_btc the bitcoin address needs to be automatically saved to the database.

I have already generated the following migration

rails g model Payment bitcoin:string

Any comments or assistance will be greatly appreciated.

Upvotes: 0

Views: 1042

Answers (1)

Josh
Josh

Reputation: 8596

It looks like BlockIo is already parsing the JSON string for you and returning a regular Ruby hash.

I would try something like this:

new_address = BlockIo.get_new_address
Payment.create( bitcoin: new_address['data']['address'] )

You'll probably want to check the status of the response new_address['status'] and make sure that the address is present before saving. But the code above should get you started.

You'll probably want to do a redirect or something like head :ok after the payment is created.

Note: you do not need to use the @ for the variable name. That is usually only used when you're passing that info to a view.

Upvotes: 1

Related Questions