Category Archives: Ruby on Rails

Adding a radius search to your Ruby on Rails 5 application and PostgreSQL

Recently one of my project need to create a functionality for location based search. I choose PostgreSQL as database because I want to use some power of PostgreSQL.

So I want to create a functionality where I can send three param in a PostgreSQL and this database will return me location within this radius.  So I want to search what locations are within X meters of these coordinates.

Using PostgreSQL is lot easier.

First you need to enable some plugin for PostgreSQL.

  CREATE EXTENSION earthdistance;

Now you can run query like:

SELECT \"franchises\".* FROM \"franchises\" WHERE (earth_box(ll_to_earth(40.810649, -73.598605), 2000) @> ll_to_earth(latitude, longitude))

You can also create a scope in rails model.

scope :within_radius, lambda {|latitude, longitude, metres| where("earth_box(ll_to_earth(?, ?), ?) @> ll_to_earth(latitude, longitude)", latitude, longitude, metres) }

And that’s it. You can call

  Franchise.within_radius(43.6422125, -79.3744256, 5000) 

and you’ll have a list of franchises within 5 km of NY.

Happy coding 🙂

Custom seed files in Ruby on Rails 5 project

For project purpose sometimes we need to create multiple seed files. We can do this by simple creating rake tasks in ruby on rails.

To create a rake task for multiple seed file you can use below code:

# lib/tasks/custom_seed.rake
namespace :db do
  namespace :seed do
    Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].each do |filename|
      task_name = File.basename(filename, '.rb').intern    
      task task_name => :environment do
        load(filename) if File.exist?(filename)

Please save this code to lib/tasks/custom_seed.rake file

Now create a folder called seeds inside your db folder: db/seeds

Now you can run any seed file from this folder by simple running below command:

# Name of the file without the .rb extension 
rake db:seed:seed_file_name 

Happy Coding 🙂

Error installing rmagick on Ubuntu

While running bundle install I am getting this error:

$ gem install rmagick Building native extensions. This could take a while...

ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. Can't install RMagick 2.13.2. Can't find Magick-config

I have solve this problem by installing rmagick and libmagick++-dev package

Install imagemagick:

sudo apt-get install imagemagick

Install rmagick:

$ sudo apt-get install libmagick++-dev

Create custom error pages dynamically in ruby on rails 4

The default status code templates are served by a Rack exception application. You can override this to be any Rack compatible app. To override this you need to add following line in your application.rb file.

# config/application.rb
config.exceptions_app = self.routes

Now we need to create ErrorsController:

class ErrorsController < ApplicationController
  def show
    @exception = env['action_dispatch.exception']
    render action: request.path[1..-1]

  def write_to_log_file
    if @exception.present?
      logger.error("Error occured: #{@exception.message}, Status: #{status_code}\n Time: #{}")


  def status_code
    params[:code] || 500

In show method we have added a function to write the exception to log file.

Now create templates for each status code in errors directory. I have created three template for 404.html.erb, 422.html.erb and 500.html.erb

# app/views/errors/404.html.haml
%h1 404 - Not Found

Now create route for this errors:

# config/routes.rb
 %w( 404 422 500 ).each do |code|
    get code, :to => 'errors#show', :code => code

And that’s it for dynamic error page.

Happy coding 🙂

Create RSS from your ruby on rails application

For one my recent project need RSS feed. So I have created myself.

This will show you how to create a RSS feed that the Feed Validator considers valid.

First create a FeedsController to host the RSS feed.

class FeedsController < ApplicationController

  layout false

  def rss
    @posts = Post.published_posts.limit(50)


Then create a view in views/feeds/rss.rss.builder for RSS.

xml.rss :version => '2.0', 'xmlns:atom' => '' do do
    xml.title 'Feed title'
    xml.description 'Feed description' root_url
    xml.language 'en'
    xml.tag! 'atom:link', :rel => 'self', :type => 'application/rss+xml', :href => posts_url

    for post in @posts
      xml.item do
        xml.title post.title
        xml.pubDate(post.created_at.rfc2822) post_url(post)
        xml.guid post_url(post)
        xml.image_url post.image_url



Create a route to the feed in config/routes.rb:

get 'feed.rss', to: 'feeds#rss', :format => 'rss'

You can get browsers to auto-detect your Rails blog rss feed with a single line of Ruby on Rails code:

<%= auto_discovery_link_tag(:rss, "") %>

That’s it.

Happy Coding 🙂

The program ‘bundle’ is currently not installed

This is a common problem when you first time install a new version of ruby. To fix this problem please follow below steps:

Step one:
Set up the PATH variable for the installed ruby executable
(Suppose the installed ruby is ruby-2.1.5):

Step two:


Step three:

gem install bundler

(if bundler is not installed)

Final Step:

rvm use ruby-2.1.5 --default

(–default is optional).

This will fix your problem.

Hope it helps 🙂

Remove model field name in rails validation

By default rails show field name before it’s default message.

For example default rails validation:

validates_xxx_of :the_column, :message =&gt; "Please add this!" will show message "The ColumnPlease add this!"

For project purposes we need some time to add custom error messages without a field name in rails validation.

We can solve this by adding custom method in model.

In rails 2: you can do on your model:

validate :test_validation


def test_validation

In rails 3 or greater:

validate :test_validation


def test_validation
errors.add(:base, 'Message')