REST API Routes with Sinatra not working - mysql

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.

Related

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.

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.
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.

Pass in user-specified parameters to query a database and return data

I am extremely new to Ruby on Rails, having only a couple days of experience. So far, I have created a new app, and loaded data into the database called name which is comprised of date:string, value:decimal, and unique_id:integer. So now, I can go to "(my local port)/name" and view the table successfully.
What I would like to do is this:
In a new html page, have a SIMILE Timeplot (http://www.simile-widgets.org/timeplot/) with an HTML drop-down list below it in order to select a unique_id and another drop-down box to select a year.
From there, I would like to search through the database and display all of the data on the Timeplot that matches the unique_id and that is in the specified year.
I believe I must make an HTTP GET request for a date_to, date_from, and unique_id, but I do not know how to implement this (admittedly I have been searching the web for ages, but could not figure out the solution).
Any help would be greatly appreciated! Thank you.
Edit: Even just advice on what component to tackle first
First you need to create a route for your search such as this:
match "name/search" to: "name#search" as: "name_search", via: :get
Then if you are using AJAX, and using jQuery you make an HTTP request like this:
$.get("/name/search", {
unique_id: <your_unique_id>,
date_from: <your_date_from>,
date_to: <your_date_to> },
function(result) {
// You do whatever you want with the result here
}
}
P.S:
The Javascript code might not be 100% correct, since I rarely use it.

rails with MySQL AND a small redis store

I've got a Rails 3.1 app running a mysql server for storing data.
90% of the data in the app fits really well in a relational database.
The other 10% is a pretty large hash that I need to pull out, change, and put back fairly quickly. It is a fairly large query in mysql to bring all these data pieces together, across multiple tables, but once I have it once, I figured I would save it as a hash, and the user can interact with the hash and make changes. Those changes never get persisted back to mysql, as mysql doesn't need them.
so, I decided to add redis to my rails application and the redis-objects gem was recommended by a friend.
I have created my active_hash model and controller as so
class ActiveHash < ActiveRecord::Base
include Redis::Objects
end
class ActiveHashesController < ApplicationController
def show
#this is a big query with a bunch of merges, but simplified here as it isn't important
active = Game.find(params[:id])
active_hash_in_redis = ActiveHash.new()
if active_hash_in_redis.save
render :json => active_hash
else
render :text => "didn't save"
end
end
end
when I navigate to active_hashes/id, I get an error that there is no MySQL table active_hashes, which is right, because that is supposed to be my redis db, as defined in the model.
can anybody explain to me how to use both dbs in my app, and/or point me to a tutorial on doing this? I haven't been able to find anything. Is using Redis-Objects the wrong way to go with this?? Any other recommendations?
It turns out this was a bit of confusion on my part, but hopefully this helps somebody else.
I didn't end up using the redis-objects, gem, I installed redis-rb with gem redis.
Then I set-up the config file as
require 'redis'
$redis = Redis.new()
My model is actually blank at the moment, in my controller, I've used
class ActiveHashesController < ApplicationController
def show
#this is a big query with a bunch of merges, but simplified here as it isn't important
active = Game.find(params[:id])
$redis.set params[:id], active.to_json
get_game = $redis.get params[:id]
render :json => get_game
end
end
end

Can't access rails post data

I've spent the last couple of hours slowly losing my mind while trying to figure something out. I'm submitting a form in rails, everything works fine until I try to access the params. In the console I can see the following:
Parameters: {"authenticity_token"=>"3mdEW2lHhkzpZbDsJCu8ZEV/wbq2YB/ztNR0RLTMZDs=", "utf8"=>"✓", "project"=>{"name"=>"woeij", "client"=>"iwej", "description"=>"oiejdoiew woeij"}, "id"=>"13"}
As you can see I'm sending name, client, description and id. I can access ID fine with something like:
#id = params[:id]
However, when I try to access name, client, or description in the same way they're all empty.
If I do:
#project = params[:project]
I get:
namewoeijclientiwejdescriptionoiejdoiew woeij
Would someone mind explaining what I'm doing wrong? And why I can't just get "woeij" when I do:
#name = params[:name]
Sorry for the stupid question, big thanks as always.
Attributes are nested, do
params[:project][:name]
to retrieve name.
A really cool tool in the rails console is the y: if you type y params they'll be presented really nicely.
You have a hash inside a hash. After you do:
#project = params[:project]
You have all your project parameters inside that hash. You can select them like this:
#project[:name] #=> "woeij"
#project[:client] #=> "iwej"
You can also select them in one go like this:
params[:project][:description] #=> "oiejdoiew woeij"