Search code examples
ruby-on-railsmongoidrails-geocoder

Rails Geocoder says "can't convert string to integer"


Im my index index controller I have @usergeo = Geocoder.search("83.215.14.101")

result is:

Geocoder::Result::Freegeoip:0x007ff3ced35eb8 @data={
"city"=>"Salzburg", 
"region_code"=>"05", 
"region_name"=>"Salzburg", 
"metrocode"=>"", 
"zipcode"=>"",
"longitude"=>"13.0333", 
"latitude"=>"47.8", 
"country_code"=>"AT", 
"ip"=>"83.215.14.101", 
"country_name"=>"Austria"},

 @cache_hit=nil>]

.class means it is an array!

In the view I try this one:

<%= @usergeo["city"] %>

and the result is

can't convert String into Integer

Also an @usergeo[:city] does not work

any comment will be very helpful to me thanks


Solution

  • Try @usergeo.first.city or @usergeo[0].city as you want to reference the @data sample in this case.

    The reason you're getting that error is because you're basically trying to call Array["city"] on the result, but an array obviously expects an integer, not a string. This way you reference the object, which is a hash, and call ["city"] on that instead.