Sometimes it can be useful to find a user’s physical location in our Rails application. For instance, maybe we want to send a special Happy Holidays to users of a particular country. IP address geolocation lets us do exactly that. With IP address geolocation you can get a pretty good idea of where the customer is accessing your site from as long as they aren’t using a proxy server or some other means of obscuring their IP address. In this article we will show you how to utilize the Maxmind GeoIP database to look up the location of just about any IP address. Let’s get started.
Setup Rails Application
To utilize the IP address geolocation functionality, we first need to add the geoip gem to our gemfile. Open up your gemfile and add in the code listed below:
Great, now let’s run a bundle install to install the gem.
Now we need to download the GeoIP database for use with the geoip gem. A free one can be downloaded at this link, or you can use the paid version if you have a subscription. Once downloaded, extract the compressed archive and place the .dat folder contained within in the root directory of your Rails app.
Great, now let’s create a controller so that we can play around with the GeoIP functionality. Run the commands below to create a controller called GeoIpRequest:
Next, open up your routes file and modify it so that it looks like the code listed below:
1 2 3 4 5
Great, now open up your GeoIpRequest controller and modify it so that it looks like the code listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
In the code above, we tell the geoip gem to load our database file and do a search for the host parameter.
Now let’s create our views. Open up the new view for the GeoIpRequest controller and modify it so that it looks like the code listed below:
1 2 3 4 5 6 7
Great, now finally let’s do the create view. Open up the create view for the GeoIpRequest controller and modify it so that it looks like the code listed below.
1 2 3 4 5
Excellent, now if you fire up your rails development server and and navigate to http://localhost:3000 you will see a form requesting your ip address or hostname. Entering any ip address or host name will show the country, city, and region that ip is from.
So far so good, that’s it!!! that’s all there is to it!!! :)