question about geocoder gem
I am using the gem 'geocoder'. I am trying to make an object that will fetch the latitude and longitude from ip address.
This is how my object's model looks like:
class 开发者_开发技巧Hey < ActiveRecord::Base
geocoded_by :ip
after_validation :geocode
def ip
return request.ip
end
end
When I create an object I get this error:
NoMethodError (undefined method `request'for #<Hey:0x7f268f47dd00>):
if I change the method ip to:
def ip
return "24.193.83.1"
end
it works. Why does request.ip
doesn't work in the model ?
request.ip
works for me in the controller.
How can I fix this?
Thanks,
Oded
This is how I solved it.
the model:
class Hey < ActiveRecord::Base
attr_accessor :ip_address
geocoded_by :ip_address
after_validation :geocode
end
controller:
class HeysController < ApplicationController
def create
hey = Hey.new
hey.ip_address = request.ip
hey.save
redirect_to :action => "index"
end
end
You also need to store ip of this object. Fill ip_address with request.ip when create new object. Than code in the model will looks like:
geocoded_by :ip_address,
:latitude => :lat, :longitude => :lon #this is also fields in the db
after_validation :geocode
or something like that.
精彩评论