Method of getting current location from IP address in Rails (geocoder and gmaps4rails gems)

谁说胖子不能爱 提交于 2019-12-13 20:39:42

问题


I have an app which allows users to post Offers based on address they choose. I would like to add the option of saving the address based on the user's current location, determined by the IP address. I'm using the ruby Geocoder gem. This code will pass but it is not saving any address to the db. I'm not sure if it's an issue with my approach or if it is not working because of the development environment. I know that other features of Geocoder e.g. distance calculations don't work in development.

current_location is a boolean attribute of the Offer class

In the offers/_form View:

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

In the OffersHelper:

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

In the Offer Model:

def geo_offer
  geocode_by_ip_address(offer)
end

For the purposes of the my map, gmaps4rails uses the following attributes:

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

However the address is not saving (have checked using the console). Would appreciate any help! Many thanks


回答1:


I'm not sure if :current_location should be a symbol in your model if block. Calling the current_location method inside an object will resolve to the boolean value of current_location (provided your controller is saving it correctly) so change the code to:

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

EDIT: Sorry just realised that this is in a helper and not the model, :current_location and current_location should both be undefined in your helper, you would need to pass that logic in (or I would put the if block inside the model and then call geocode_by_ip_address with the if block removed from there)



来源:https://stackoverflow.com/questions/18934213/method-of-getting-current-location-from-ip-address-in-rails-geocoder-and-gmaps4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!