Reputation: 2118
I just included the Geocoder gem into my app. Everything works perfect but i was wondering if i can user the gem even further.
My application has got users and they are allowed to add articles. At the moment i can their IP address using
@article.ip_address = request.remote_ip
I have looked for a gem which can help me convert that IP address to country name but i can't find anything. Since i am using geocoder and i realize that on their website they auto detect my IP, City and Country. I was wondering how i can implement this to my controller.
def create
@article = Breeder.new(params[:breeder])
@article.user = current_user
@article.ip_address = request.remote_ip
respond_to do |format|
if @article.save
format.html { redirect_to @article, notice: 'Article was successfully created.' }
format.json { render json: @article, status: :created, location: @article }
else
format.html { render action: "new" }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
The idea is to detect articles which are not from the UK.
https://github.com/alexreisner/geocoder
Upvotes: 4
Views: 1622
Reputation: 523
Yes, you can use Geocoder to geocode IP address. Geocoder would adds a location methods to Request so you just need to:
sender_ip = request.remote_ip
sender_country = request.location.country
sender_city = request.location.city
That works for me. Hope it helps.
Upvotes: 0
Reputation: 3878
You can use geoip gem.
Download GeoIP.dat.gz from http://www.maxmind.com/app/geolitecountry. unzip the file. The below assumes under #{RAILS_ROOT}/db dir.
@geoip ||= GeoIP.new("#{RAILS_ROOT}/db/GeoIP.dat")
remote_ip = request.remote_ip
if remote_ip != "127.0.0.1" #todo: check for other local addresses or set default value
location_location = @geoip.country(remote_ip)
if location_location != nil
@model.country = location_location[2]
end
end
Upvotes: 4
Reputation: 8954
Maybe GeoIP is an alternaternative for you:
https://github.com/cjheath/geoip
Its really simple. Im not that confident to geocoder but if you definitfly want to use it you might watch the railscast that deals with it.
http://railscasts.com/episodes/273-geocoder
Rails coding women, damn hot!^^
Upvotes: 0