Rails中Ruby Geocoder gem的问题

时间:2013-10-02 22:09:52

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

我有一个模型,商品,我正在尝试从用户那里获取IP地址,并按纬度和经度对坐标进行地理编码。 gem文档指出知道ip地址的地方代码应为:

型号:

      geocoded_by :ip_address, :latitude => :latitude, :longitude => :longitude

但是我最初没有保存IP地址所以我将其更改为:

if :current_location
self.ip_address = request.ip
          geocoded_by :ip_address, :latitude => :latitude, :longitude => :longitude
end

request.ip是ActionView的一个方法,我相信不能从模型中调用。我已将此测试为辅助方法,并返回本地:主机地址。但是当我尝试以这种格式保存它时,它不会保存任何模型。

将ip_address保存到模型的最佳方法是什么,以便以这种格式使用?它应该被提取到辅助方法吗?有没有办法在模型中使用includerequire正确的模块?

作为参考,宝石指南在这里:http://www.rubygeocoder.com

所有帮助表示感谢,谢谢。

2 个答案:

答案 0 :(得分:1)

您可能希望直接使用Geocoder类,而不是在模型中使用geocoded_by方法。我将创建一个处理商品创建的服务对象。您可以通过执行以下操作找到ip_address的坐标:

Geocoder.coordinates(ip_address) # => [latitude, longitude]

我会做以下事情:

class OfferGeocoder
  attr_reader :request, :params, :coordinates

  def initialize options = {}
    @request = options[:request]
    @params = options[:params]
  end

  def coordinates
    @coordinates ||= Geocoder.coordinates(request.remote_ip)
  end

  def create_offer
     Offer.new(params.merge({
       latitude: coordinates.first,
       longitude: coordinates.last
     })
  end
end

在您的控制器的创建操作中,您可以致电:

def create
   @offer = OfferGeocoder.new(params: offer_params, request: request).create_offer
   if @offer.save
     ...
end

答案 1 :(得分:0)

好的,因为方法request.ip在模型中不起作用,最简单的方法是通过控制器:

class OffersController<ApplicationController

 def create
    @offer = Offer.new(offer_params)
    if @offer.current_location
    @offer.ip_address = request.ip

...
  end
end

此外,request.ip方法在开发模式下不起作用,因为它返回本地主机地址而不是真正的IP地址。