Ruby on rails 将登录位置保存到my rails应用程序的数据库中
当我登录应用程序时,将调用下面的代码。因此,在SessionController中,使用.create方法填充SignupHistory表 应用程序\u controller.rb 会话\u controller.rb 数据库属性 但是,要将IP登录的位置写入数据库(如纽约),我在数据库中得到的是: --!!ruby/object:Geocoder::Result::Ipstack数据:ip:127.0.0.1国家/地区名称:保留国家/地区代码:RD缓存命中率: 如何将基于IP登录的位置保存到数据库中您可以使用request.remote\u IP获取IP地址。 要获取保存在DB中的IP地址的位置,您可以使用其中一个免费API服务获取基于IP的位置信息: - - -等等 参考:Ruby on rails 将登录位置保存到my rails应用程序的数据库中,ruby-on-rails,ruby,ruby-on-rails-4,geocoder,Ruby On Rails,Ruby,Ruby On Rails 4,Geocoder,当我登录应用程序时,将调用下面的代码。因此,在SessionController中,使用.create方法填充SignupHistory表 应用程序\u controller.rb 会话\u controller.rb 数据库属性 但是,要将IP登录的位置写入数据库(如纽约),我在数据库中得到的是: --!!ruby/object:Geocoder::Result::Ipstack数据:ip:127.0.0.1国家/地区名称:保留国家/地区代码:RD缓存命中率: 如何将基于IP登录的位置保存到数
请求包含什么?老实说,我甚至不知道,我也不知道如何检查请求包含的内容。只需在save_signup_history方法中进行raise request.inspect并将输出粘贴到问题中。这是您通过localhost访问应用程序的数据吗?是的,来自localhost,但我已使用IP:request.IP将IP保存到数据库中。我正在尝试获取您从纽约登录的位置,它记录纽约,如果从伦敦登录,它记录London@AfolabiOlaoluwaAkinwumi我以为你有IP问题,因为我可以你是显示本地主机IP@AfolabiOlaoluwaAkinwumi你需要使用一种服务,比如获取你拥有的IP地址的位置。你能展示一下使用iplocation.net的例子吗,而不丢失我对id的请求参数?好的,我看到了你非常漂亮的更新。非常感谢。所以,如果我需要返回regionName和country,我可以执行result[regionName]&&result[country]?这样我就可以把美国纽约保存在数据库里。
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
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
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
{
"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"
}