Ruby Heroku 上的地理编码器生成私有 IP 地址

Ruby geocoder on Heroku yields private IP address

Ruby Geocoder (http://rubygeocoder.com/) 可以很好地获取已知地址的纬度和经度。现在我正尝试使用它通过 IP 地址查找国家代码,这样新用户就不必 select 他们的国家。

if @person.country.blank?
    ip_loc = Geocoder.search(my_ip_address)
    if ip_loc.present?
       @person.country = ip_loc[0].data['country_code']
    end
end

为了获取他们的 IP 地址以提供给 Geocoder,我正在使用套接字:

 def my_ip_address
    require 'socket'
    list=Socket.ip_address_list
    ip = list.detect{|intf| intf.ipv4_private?}
    ip.ip_address if ip
 end

由于 IP 查找不适用于开发机器(IP 地址始终是私有的内部号码),我正在尝试在 Heroku 上进行测试。

然而,当它在 Heroku 上运行时,我仍然得到一个私有 IP 地址 172.19.75.142,无法使用 Geocoder 查找。

有人可以指导我从可在 Heroku 上运行的 IP 获取国家/地区的有效方向吗?

您可以通过request.remote_ip获取user/client的IP地址。然后您应该能够将此值输入 Geocoder。

请注意,request 仅在您的控制器中可用。