Rails中如何保存HTTP请求结果?及将Curl响应数据存入数据表
Hey there! Let's break this down into two clear, actionable parts: saving your token response data to a Rails database table, and logging all the details of your HTTP request. Here's a step-by-step guide for both:
First, you'll need a model to store the token data that matches the structure of your API response.
Step 1: Generate the Model
Run this in your terminal to create a UserToken model (feel free to rename it if it makes more sense for your app):
rails generate model UserToken \ access_token:string \ public_key:string \ refresh_token:string \ live_mode:boolean \ user_id:integer \ token_type:string \ expires_in:integer \ scope:string
Then run the migration to create the corresponding database table:
rails db:migrate
Step 2: Parse the Response & Save the Data
Update your existing Net::HTTP code to parse the JSON response and persist it to the database. Here's how to adjust your code:
# Your existing request setup uri = URI("your-api-endpoint-url") request = Net::HTTP::Post.new(uri) # Add any required request headers/body (e.g., auth credentials, content type) request["Content-Type"] = "application/json" request.body = JSON.generate({ your_request_params: "value" }) req_options = { use_ssl: uri.scheme == "https" } response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| http.request(request) end # Parse and save the token data begin token_data = JSON.parse(response.body) # Create the record—Rails auto-maps JSON keys to your model's columns UserToken.create!(token_data) puts "Token data saved successfully!" rescue JSON::ParserError => e puts "Failed to parse API response: #{e.message}" rescue ActiveRecord::RecordInvalid => e puts "Failed to save token data: #{e.message}" end
- The
create!method raises an error if validation fails, so wrapping it in arescueblock helps handle unexpected issues gracefully instead of crashing your app.
To log every detail of your Net::HTTP call (request method, URL, headers, body, and response data), create a dedicated RequestLog model.
Step 1: Generate the RequestLog Model
Run this command (we use jsonb for headers if you're on PostgreSQL—it’s great for querying later; if you’re on SQLite, swap jsonb for text):
rails generate model RequestLog \ request_method:string \ url:string \ request_headers:jsonb \ request_body:text \ response_status:integer \ response_headers:jsonb \ response_body:text
Run the migration:
rails db:migrate
Step 2: Log the Request & Response
Modify your code to collect and save the request/response data right after making the API call:
# Your existing request setup (same as before) uri = URI("your-api-endpoint-url") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request.body = JSON.generate({ your_request_params: "value" }) req_options = { use_ssl: uri.scheme == "https" } response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| http.request(request) end # Gather all request/response details log_data = { request_method: request.method, url: uri.to_s, request_headers: request.to_hash, # Converts headers to a hash for jsonb storage request_body: request.body, response_status: response.code.to_i, response_headers: response.to_hash, response_body: response.body } # Save the log entry begin RequestLog.create!(log_data) puts "Request log saved successfully!" rescue ActiveRecord::RecordInvalid => e puts "Failed to save request log: #{e.message}" end
Bonus: Link Token Data to Request Log
If you want to connect the saved token to the request that generated it, add an association between the two models:
- Add a reference column to
user_tokens:rails generate migration AddRequestLogToUserTokens request_log:references rails db:migrate - Update your models to define the association:
# app/models/user_token.rb class UserToken < ApplicationRecord belongs_to :request_log end # app/models/request_log.rb class RequestLog < ApplicationRecord has_one :user_token end - Update your save code to link the records:
request_log = RequestLog.create!(log_data) UserToken.create!(token_data.merge(request_log: request_log))
Important Notes
- Sensitive Data: Fields like
access_tokenandrefresh_tokenare sensitive. Consider encrypting them with a gem likeattr_encryptedto keep them secure in your database. - Validation: Add validations to your models (e.g.,
validates :access_token, presence: true) to ensure data integrity. - Cleanup: If you don't need old logs/tokens forever, set up a background job (like with Sidekiq) to delete records after a set period to keep your database lean.
内容的提问来源于stack exchange,提问作者Sebastian Ruiz Perez

