How to automatically save data from API - Ruby on Rails - json

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.

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.

Related

Generating an auto incrementing number in rails

I am very new to rails and was wondering if someone might be able to help me.
I need to generate and save an auto incrementing number for an invoicing. Ive already created the field 'invoicenum:integer' in my billing_history table.
I was wondering how I can do this from the controller ? This is the entry point where I was wanting to put it. Im not sure how I would write the function to create this incrementing number... Do i write it inside this function or do i create another function outside of this and just call it ?
transaction.company.billing_history.create!(
reference: transaction.description,
amount: transaction.amount,
plan: transaction.plan,
status: 'success',
invoicenum:
)
it's more preferable to make your controller slim so for a code like this its better to be on the model
lets say you have
BillingHistory.rb
you could set a callback to generate the invoice number like this
class BillingHistory < ApplicationRecord
before_create :generate_invoice_number
private
def generate_invoice_number
# logic for generating invoice number
# adjust accordingly to your needs
self.invoicenum = BillingHistory.maximum(:invoicenum).next
end
end
this will assign the value of BillingHistory.invoicenum before validated

What is the URL when I DELETE an object

I'm running a local server playing around with an API using Django. I have a model called 'Users' populated with a few objects, and am using DefaultRouter.
I want to know what the URL would be if I were to DELETE a specific object from this model. For example, if I wanted to GET a user with an ID of 1 in this model, the URL would be: "localhost:8000/Users/1/". What would the equivalent be to DELETE this user?
I found an explanation of this on the REST API website (below), however, I don't understand what any of the syntaxes means.
What is {prefix}, {url_path}, {lookup} and [.format]? If anyone could provide an example of what this might be using a localhost that would be really helpful.
Thanks
Let us take an example of an API (URL) to update book data with id (pk) being 10. It would look something like this:
URL: http://www.example.com/api/v1/book/10/
Method: PUT/PATCH
With some data associated.
If you want to delete you just need to change method to DELETE instead of put or patch.
Regarding your second question lets compare the url with the parameters.
prefix: http://www.example.com/api/v1/book
lookup: 10
format: It specifies what type of data do you expect when you hit the API. Generally it is considered to be json.
url_path: In general, every thing after look up except query string is considered to be url_path.

Getting the value of a particular cell with AJAX

My goal is very simple and I would guess it is a very common goal among web developers.
I am creating a Rails (5.1) application, and I simply want to use AJAX to get the value of a specific cell in a specific row of a specific table in my database (later I am going to use that value to highlight some text on the current page in the user's browser).
I have not been able to find any documentation online explaining how to do this. As I said, it seems like a basic task to ask of jquery and ajax, so I'm confused as to why I'm having so much trouble figuring it out.
For concreteness, say I have a table called 'animals', and I want to get the value of the column 'species' for the animal with 'id' = 99.
How can I construct an AJAX call to query the database for the value of 'species' for the 'animal' with 'id' = 99 .
Though some DBs provide a REST API, what we commonly do is define a route in the app to pull and return data from the DB.
So:
Add a route
Add a controller/action for that route
In that action, fetch the data from the DB and render it in your preferred format
On the client-side, make the AJAX call to that controller/action and do something with the response.

Passing parameters from form to controller using RoR

I am new to RoR development and am a little confused about how parameters are passed from a HTML view to the controller. I have seen a few examples online which use a private method like this:
private
def message_params
params.require(:message).permit(:content)
end
I have been looking for some clarification online as to what this method does and how it works, but I only encounter posts/articles which use the method rather than explain what it does.
I was hoping someone could explain how the method takes(/filters?) values passed via the form via a POST request, what the require and permit keywords mean and how would i change this method to fit my own use.
For example if i needed to get data about a new book would i do this:
private
def book_params
params.require(:book_name).require(:ISBN).require(:Author).permit(:Illustrator)
end
Would the above be valid given that my book object has those fields?
Any clarification would be appreciated.
Thank you.
here is some info (I'm using your sample model Book and BookController), that probably can help you more understand
when you submit form, rails automatically called create method, inside create method you will see Book.new(book_params), book_params will call private method and will check which field allowed, if there is another field that submitted but not listed inside your permit block then it will be not passed along to save command
class BooksController < ApplicationController
def create
#book = Book.new(book_params)
if #book.save
flash[:success] = 'Data save successfully'
redirect_to books_path
else
render :new
end
end
private
def book_params
params.require(:book).permit(
:book_name,
:isbn,
:author,
:illustrator)
end
end
This kind of function is used to whitelist params - ie say you have a message model, and through the controller actions you should only be able to change the content. Maybe there is also an author field - but even if someone were to pass that through the form, you would not want to update it.
params.require(:message)
Will return to you params[:message]. permit means you are allowing only the content field through.
See: http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters
I would need to see your model setup, but I would assume given a book model you'd want something more akin to:
params.require(:book).permit(:illustrator, :author, :isbn)

REST API Routes with Sinatra not working

I'm trying to create a simple Sinatra app that pulls a slew of postal codes from the database and render it in JSON. I have two get statements right now
get '/postalcodes' do
PostalCodes.all.to_json only: [:CountryCode, :PostalCode, :PlaceName, :AdminName1, :AdminCode1, :AdminName2, :AdminCode2, :AdminName3, :AdminCode3, :Latitude, :Longitude, :Accuracy]
end
get '/postalcodes/:countrycode' do
PostalCodes.find(params[:countrycode]).to_json only: [:CountryCode, :PostalCode, :PlaceName, :AdminName1, :AdminCode1, :AdminName2, :AdminCode2, :AdminName3, :AdminCode3, :Latitude, :Longitude, :Accuracy]
end
The first GET works fine but I would expect that I could enter the URI:
localhost:3000/postalcodes/US
to get all the postal codes with the country code of 'US'. Well, it's not working.
Assuming that you're using activerecord handling the database for PostalCodes, you would do it like so:
PostalCodes.where("CountryCode" => params[:countrycode].to_s).all
I made further assumptions about column names in your database, so I hope the basic idea comes across even if the specific code might not work.