ruby-on-rails - 将登录位置保存到我的 rails 应用程序的数据库中
问题描述
当我登录应用程序时,会调用下面的代码。因此,在 SessionsController 中,SignupHistory 表被填充了该.create
方法。
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
before_action :set_timezone, :current_country
def current_country
if session[:ip_country_code].present?
return @current_country = session[:ip_country_code]
end
use_default = request.location.nil? || request.location.country_code.blank? || request.location.country_code == 'RD'
country_code = use_default ? ENV['DEFAULT_IP_COUNTRY_CODE'] : request.location.country_code
@current_country = session[:ip_country_code] = country_code
end
end
session_controller.rb
class SessionsController < ApplicationController
def save_signup_history(member_id)
SignupHistory.create(
member_id: member_id,
ip: request.ip,
accept_language: request.headers["Accept-Language"],
ua: request.headers["User-Agent"],
login_location: request.location
)
end
end
数据库属性
但是,我在数据库中得到的不是login_location: request.location
将登录 IP 的位置写入数据库的行,而是:New York
--- !ruby/object:Geocoder::Result::Ipstack data: ip: 127.0.0.1 country_name: Reserved country_code: RD cache_hit:
如何根据登录到我的数据库的 IP 保存位置
解决方案
您可以使用它request.remote_ip
来获取 IP 地址。要获取保存在 DB 中的 IP 地址的位置,您可以使用基于 IP 获取位置信息的免费 API 服务之一:
- http://ip-api.com/
- https://www.iplocation.net/
- ETC..
class SessionsController < ApplicationController
require 'net/http'
require 'json'
def save_signup_history(member_id)
SignupHistory.create(
member_id: member_id,
ip: request.ip,
accept_language: request.headers["Accept-Language"],
ua: request.headers["User-Agent"],
login_location: get_address(request.remote_ip)
)
end
#http://ip-api.com/json/208.80.152.201
def get_address(ip)
url = "http://ip-api.com/json/#{ip}"
uri = URI(url)
response = Net::HTTP.get(uri)
result = JSON.parse(response)
result["regionName"] # returns region name
end
end
JSON响应:
{
"as":"AS14907 Wikimedia Foundation, Inc.",
"city":"San Francisco (South Beach)",
"country":"United States",
"countryCode":"US",
"isp":"Wikimedia Foundation, Inc.",
"lat":37.787,
"lon":-122.4,
"org":"Wikimedia Foundation, Inc.",
"query":"208.80.152.201",
"region":"",
"regionName":"California",
"status":"success",
"timezone":"America/Los_Angeles",
"zip":"94105"
}
参考:
https ://apidock.com/rails/ActionController/Request/remote_ip
推荐阅读
- node.js - Heroku 连接 MONGO 地图集
- angular-reactive-forms - 自定义控件不更新父表单验证
- amazon-web-services - 如何阻止 Terraform 删除导入的资源?
- tsibble - 从 tsibble (Fable) 下载预测值
- c# - 有没有办法为您正在单元测试的类设置配置设置?
- ionic-framework - 离子应用程序的 Highchart 组织结构图类型错误
- html - 由于 CORS 政策,无法在 WordPress 网站中加载字体
- angular - Angular canDeactivate 不起作用并且值显示为 null
- java - Android Studio App startet nicht aber mein Code ist nicht Schuld
- php - Codeigniter - 无法访问以“\0”错误开头的属性