如何在 Rails 上自动保存来自 API - Ruby 的数据
How to automatically save data from API - Ruby on Rails
我在互联网上搜索过,但是,我似乎无法在这个问题上得到明确的答案。我正在使用 Block.io API 将比特币支付添加到我的应用程序中。我收到一个 JSON 散列,其中包含每次付款的新比特币地址,我可以提取比特币地址,但我需要它自动保存到我的数据库中,当用户访问特定页面时,地址也会生成在那个页面上。我正在使用 Postgresql
JSON 看起来像这样:
{"status"=>"success", "data"=>{"network"=>"BTCTEST", "address"=>"2MstFNxtnp3pLLuXUK4Gra5dMcaz132d4dt", "available_balance"=>"0.01000000", "pending_received_balance"=>"0.00000000"}}
我有一个控制器调用 API 来生成地址:
class PaymentsController < ApplicationController
def index
@new_address = BlockIo.get_new_address
end
end
比特币地址显示使用:
<%= @new_address["data"]["address"] %>
我正在考虑创建一个新函数,将比特币地址保存到数据库中,并在访问特定页面时映射执行此函数的路由,例如:
控制器:
class PaymentsController < ApplicationController
def create
@new_address = BlockIo.get_new_address
## I need assistance with the rest to auto save
end
end
路线:
match '/save_btc' => 'payments#create', via: [:get, :post]
当有人打开域时。com/save_btc比特币地址需要自动保存到数据库中。
我已经生成了以下迁移
rails g model Payment bitcoin:string
如有任何意见或帮助,我们将不胜感激。
看起来 BlockIo
已经在为您解析 JSON 字符串并返回一个常规的 Ruby 散列。
我会尝试这样的事情:
new_address = BlockIo.get_new_address
Payment.create( bitcoin: new_address['data']['address'] )
您可能需要检查响应的状态 new_address['status']
并确保在保存之前地址存在。但是上面的代码应该可以帮助您入门。
您可能希望在创建付款后进行重定向或类似 head :ok
的操作。
注意:变量名不需要使用@
。这通常仅在您将该信息传递给视图时使用。
我在互联网上搜索过,但是,我似乎无法在这个问题上得到明确的答案。我正在使用 Block.io API 将比特币支付添加到我的应用程序中。我收到一个 JSON 散列,其中包含每次付款的新比特币地址,我可以提取比特币地址,但我需要它自动保存到我的数据库中,当用户访问特定页面时,地址也会生成在那个页面上。我正在使用 Postgresql
JSON 看起来像这样:
{"status"=>"success", "data"=>{"network"=>"BTCTEST", "address"=>"2MstFNxtnp3pLLuXUK4Gra5dMcaz132d4dt", "available_balance"=>"0.01000000", "pending_received_balance"=>"0.00000000"}}
我有一个控制器调用 API 来生成地址:
class PaymentsController < ApplicationController
def index
@new_address = BlockIo.get_new_address
end
end
比特币地址显示使用:
<%= @new_address["data"]["address"] %>
我正在考虑创建一个新函数,将比特币地址保存到数据库中,并在访问特定页面时映射执行此函数的路由,例如:
控制器:
class PaymentsController < ApplicationController
def create
@new_address = BlockIo.get_new_address
## I need assistance with the rest to auto save
end
end
路线:
match '/save_btc' => 'payments#create', via: [:get, :post]
当有人打开域时。com/save_btc比特币地址需要自动保存到数据库中。
我已经生成了以下迁移
rails g model Payment bitcoin:string
如有任何意见或帮助,我们将不胜感激。
看起来 BlockIo
已经在为您解析 JSON 字符串并返回一个常规的 Ruby 散列。
我会尝试这样的事情:
new_address = BlockIo.get_new_address
Payment.create( bitcoin: new_address['data']['address'] )
您可能需要检查响应的状态 new_address['status']
并确保在保存之前地址存在。但是上面的代码应该可以帮助您入门。
您可能希望在创建付款后进行重定向或类似 head :ok
的操作。
注意:变量名不需要使用@
。这通常仅在您将该信息传递给视图时使用。