首页 > 解决方案 > 将登录位置保存到我的 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 保存位置

标签: ruby-on-railsrubyruby-on-rails-4geocoder

解决方案


您可以使用它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


推荐阅读