Rails Geocoder “undefined method error”

删除回忆录丶 提交于 2019-12-11 07:58:54

问题


Another true newbie on Ruby here, so please be gentle... I'm working with alexreisner's Geocoder on rails 3.0 and am unable to call methods from the Geocoder::Results lib. I've pored over the Geocoder documentation, but I can't accomplish one simple thing: pull out a "state" result from a user-submitted address. So turn "123 Fake Street, San Francisco, CA" into "CA" or "California."

(My program will only use the "state" information for now to help determine results, but I'd like to have full address information to use at a later date when I refine the app, which is why I ask for a full address.)

I've set up my model via the best I have been able to gather from the documentation and other answers I've found here, but previous answers similar to this subject have not helped me:

class Project < ActiveRecord::Base                    
  attr_accessible :title, :address, :latitude, :longitude     

  belongs_to :user 

  geocoded_by :address
  after_validation :fetch_coordinates

  reverse_geocoded_by :latitude, :longitude do |obj, geo| 
    obj.state = geo.state
    obj.country_code = geo.country_code
    obj.address = [geo.state, geo.country_code].join(",")
  end
  after_validation :reverse_geocode  

end

But this turns up an "undefined error method" for state, country code and address. I don't understand because the documentation for the Geocoder gem clearly provides these methods. My model seems simply unable to access them. (For the record, my model IS able to pull latitude and longitude from an entered address, so it does seem Geocoder is configured correctly. And the method "geocoded_by" works great. Furthermore, it is properly set to the Google API).

I'm pretty sure I'm missing something straightforward here. In the rails console, I'm even able to use Geocoder.search("Miami, FL") and pull all county, state and city information, but I just can't seem to extract "state" via my model.

Thanks for any help!


回答1:


If you look at the examples on the Geocoder site, you'll see that the second value yielded to the block seems to be an array or some other form of collection, so you can't directly call the methods on it. Instead you first have to pull the right object out of it:

reverse_geocoded_by :lat, :lon do |obj,results|
  if geo = results.first
    obj.city    = geo.city
    obj.zipcode = geo.postal_code
    obj.country = geo.country_code
  end
end



回答2:


Be sure that you restart rails server. I ran into a situation where the geocoding worked great in rails console but gave me a undefined method 'geocoded_by' in my app. It appears as though this wasn't your reason for getting the same error, but it was mine.



来源:https://stackoverflow.com/questions/7865281/rails-geocoder-undefined-method-error

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