从Rails(geocoder和gmaps4rails gems)中的IP地址获取当前位置的方法

时间:2013-09-21 15:13:15

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

我有一个应用程序,允许用户根据他们选择的地址发布优惠。我想根据用户的当前位置添加保存地址的选项,由IP地址决定。我正在使用红宝石Geocoder宝石。此代码将通过,但它不会将任何地址保存到数据库。我不确定这是我的方法的问题,还是由于开发环境而无法正常工作。我知道Geocoder的其他功能,例如距离计算在开发中不起作用。

current_location是商品类的布尔属性

在offer / _form中查看:

<div class="field"><br>
      <%= f.label :use_current_location? %>
      <%= f.check_box :current_location %>
</div>

在OffersHelper:

def geocode_by_ip_address(offer)
    if :current_location
      offer.address = request.location.address
    end
end

在优惠模式中:

def geo_offer
  geocode_by_ip_address(offer)
end

出于我的地图的目的,gmaps4rails使用以下属性:

def gmaps4rails_address
    "#{self.address}, #{self.city}, #{self.country}"
end

但地址未保存(已使用控制台检查)。非常感谢任何帮助!非常感谢

1 个答案:

答案 0 :(得分:0)

我不确定:如果阻止,current_location应该是模型中的符号。在对象中调用current_location方法将解析为current_location的布尔值(假设您的控制器正确保存它),因此将代码更改为:

def geocode_by_ip_address(offer)
    if current_location
      offer.address = request.location.address
    end
end
编辑:很抱歉只是意识到这是一个帮手,而不是模型,:current_location和current_location都应该在你的助手中未定义,你需要传递那个逻辑(或者我会把if块放在模型中然后调用geocode_by_ip_address并从那里删除if块)