How to generate dynamic error page in Rails

How to generate dynamic error page in rails?

Step: #1

Run command for generating errors controller & view:

$ rails generate controller errors not_found internal_server_error unacceptable

Step: #2

Edit controller like below code:

class ErrorsController < ApplicationController
  def not_found
      render(:status => 404)

  def unacceptable
      render(:status => 422)

  def internal_server_error
      render(:status => 500)

Step: #3

Configure routes.rb

match "/404", to: "errors#not_found", via: :all
match "/500", to: "errors#internal_server_error", via: :all
match "/422", to: "errors#unacceptable", via: :all

Step: #4

Configure application.rb

config.exceptions_app = self.routes

Step: #5

Remove default template from public folder like 500.html, 404.html, 422.html

Step: #6

Restart your server then

Step: #7

Test localhost:3000/500, localhost:3000/404,  localhost:3000/422

Step: #8 For development

config.consider_all_requests_local = false


Happy coding!

How to Add Complex Search Term on Rails?

Today, we will learn how to implement Complex Search Term on Rails, also how to install Bootstrap with Bower and generate fake data with Faker gem.



Install new project with name “complex_search”-

$ rails new complex_search -d postgresql

Configure database.yml file inside config-

# config/database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  username: postgres # Based on your username
  password: 123456 # Based on your password
  # For details on connection pooling, see rails configuration guide
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

Then open your command prompt & write below command for database migration-

$ cd complex_search
$ bundle exec rake db:create
$ bundle exec rake db:migrate
$ bundle exec rails server

Write localhost:3000 to your browser & will show below image-

We just completed the project setup, now needs to setup Bootstrap.

There are three ways to install Bootstrap into a Rails application: as a Ruby Gem, by referencing a publicly available version hosted on a CDN, or by downloading it and storing it within our application’s source.

We’re going to use that latter, assisted by a tool called Bower.
To install Bootstrap using Bower, we’ll first need to install Bower;  then we’ll instruct it to download and install Bootstrap; and, finally, we’ll configure the asset pipeline to make Bootstrap available.
Install Bower

Bower itself as a package manager for the web. It was created by Twitter and is analogous to RubyGems, but manages front-end assets (including CSS frameworks like Bootstrap and JavaScript libraries like Angular). Bower is written in JavaScript, and so it requires a JavaScript runtime in order to work. That means you’ll have to install Node JS.

Once you have Node JS installed, you’ll have access to the npm command-line application. This is a package manager for JavaScript, and we’ll use that to install Bower.
$ npm install -g bower


# complex_search/Gemfile
gem 'bower-rails'

We can install with bundler.

$ bundle install

We have to create Bowerfile file in the root directory then install Bootstrap.

# complex_search/Bowerfile
asset 'bootstrap-sass-official'


$ bundle exec rake bower:install

Add bootstrap to our asset pipeline

# complex_search/app/assets/stylsheet/application.css
*= require_tree.
*= require_self
➤ *= require 'bootstrap-sass-official'

We are just done with installing Bootstrap with Bower!

Now we will generate a model called Customer for implementing complex search term-

$ rails generate model Customer first_name:string last_name:string email:string username:string

The migration file created & look like below-

# complex_search/db/migrate/timestamps_create_customers.rb
class CreateCustomers < ActiveRecord::Migration[5.0]
  def change
    create_table :customers do |t|
      t.string :first_name, null: false
      t.string :last_name, null: false
      t.string :email, null: false
      t.string :username, null: false

      t.timestamps null: false

    add_index :customers, :email, unique: true
    add_index :customers, :username, unique: true

Then execute following command-

$ rake db:migrate
This will create a “customers” table in database, now generate fake data for implementing search query.
Adding faker gem-
# complex_search/Gemfile
gem 'faker'

Then, we’ll install it the gem-

$ bundle install

After that-

# complex_search/db/seeds.rb
500.times do |i|
    first_name: Faker::Name.first_name,
    last_name: Faker::Name.last_name,
    username: "#{Faker::Internet.user_name}#{i}",
    email: Faker::Internet.user_name + i.to_s + "@#{Faker::Internet.domain_name}")

Then execute the above code-

$ bundle exec rake db:seed

We just created 500 fake data (rows) in database!

Building the search UI

$ rails generate controller customers index
# complex_search/config.routes.rb
resources :customers, only: [:index]
# complex_search/app/controller/customers_controller.rb

class CustomersController < ApplicationController
  	def index
  		@customers = Customer.all.limit(10)
# complex_search/app/views/customers/index.html.erb

<h1>Customer Search</h1>
<section class="search-form">
  <%= form_for :customers, method: :get do |f| %>
    <div class="input-group input-group lg">
      <%= label_tag :keywords, nil, class: "sr-only" %>
      <%= text_field_tag :keywords, nil, placeholder: "First Name, Last Name, or Email Address", class: "form-control input-lg" %>
      <span class="input-group-btn">
        <%= submit_tag "Find Customers", class: "btn btn-primary btn-lg" %>
  <% end %>

<section class="search-results">
       <h1 class="h3">Results</h1>

  <ol class="list-group">
    <% @customers.each do |customer| %>
      <li class="list-group-item clearfix">
        <h3 class="pull-right">
          <small class="text-uppercase">Joined</small>
          <%= l customer.created_at.to_date %>
        <h2 class="h3">
          <%= customer.first_name %> <%= customer.last_name %>
          <small><%= customer.username %></small>
        <h4><%= %></h4>
    <% end %>

Now create a file inside models called “customer_search_term.rb” and then write following code-

# complex_search/app/models/customer_search_term.rb
class CustomerSearchTerm
  attr_reader :where_clause, :where_args, :order

  def initialize(search_term)
    search_term = search_term.downcase
    @where_clause = ""
    @where_args = {}
    if search_term =~ /@/

  def build_for_name_search(search_term)
    @where_clause << case_insensitive_search(:first_name)
    @where_args[:first_name] = start_with(search_term)

    @where_clause << " OR #{case_insensitive_search(:last_name)}"
    @where_args[:last_name] = start_with(search_term)

    @order = "last_name asc"

  def build_for_email_search(search_term)
    @where_clause << case_insensitive_search(:first_name)
    @where_args[:first_name] = start_with(extract_name(search_term))
    @where_clause << " OR #{case_insensitive_search(:last_name)}"
    @where_args[:last_name] = start_with(extract_name(search_term))

    @where_clause << " OR #{case_insensitive_search(:email)}"
    @where_args[:email] = search_term

    @order = "lower(email) = " + ActiveRecord::Base.connection.quote(search_term) + "desc, last_name asc"

  def start_with(search_term)
    search_term + "%"

  def case_insensitive_search(field_name)
    "lower(#{field_name}) like :#{field_name}"

  def extract_name(email)

Then modify code in controller file-

# complex_search/app/controllers/customers_controller.erb
class CustomersController < ApplicationController
  PAGE_SIZE = 10
  	def index
  		if params[:keywords].present?
  			@keywords = params[:keywords]
  			customer_search_term =
  			@customers = Customer.where(customer_search_term.where_clause, customer_search_term.where_args).order(customer_search_term.order)
  			@customers = []

And that’s all! We have implemented a full & complex search feature on the Rails project.

Happy coding 🙂


Setup Ruby on Rails with Windows

How to Setup Ruby on Rails with Windows?

Requirements: Windows OS (10/8/7), Ruby Installer v2.3 or upper

At first, we need to install Ruby on our system.

  • Go to Ruby official site then download the latest version of Ruby, then install it on your specific location.
    #=> After installing ruby check the version
    $ ruby -v
    ruby 2.3.1p112 # Or somthing like this
  • Then download Development Kit from the same link as above.
  • Create a folder which called devkit inside the Ruby folder
  • Extract downloaded devkit inside the devkit folder
  • Run command inside the devkit folder
    $ ruby dk.rb init
    $ ruby dk.rb install
  • Run command inside the ruby folder “gem install rails”
    $ gem install rails 
    #=> After installing rails check version
    $ rails -v
    Rails 5.0.6
  • Create rails project
    $ rails new project
    #=> After created project then below command
    $ cd project
    $ bundle install
    #=> Configure database
    $ bundle exec rake db:create
    $ bundle exec rake db:migrate
    $ rails server
    => Booting Puma
    => Rails 5.0.6 application starting in development on http://localhost:3000
    => Run `rails server -h` for more startup options
    *** SIGUSR2 not implemented, signal based restart unavailable!
    *** SIGUSR1 not implemented, signal based restart unavailable!
    *** SIGHUP not implemented, signal based logs reopening unavailable!
    Puma starting in single mode...
    * Version 3.10.0 (ruby 2.3.1-p112), codename: Russell's Teapot
    * Min threads: 5, max threads: 5
    * Environment: development
    * Listening on tcp://
    Use Ctrl-C to stop


  • Open the browser. Write “localhost:3000” on address bar and press Enter key.


That’s all! Enjoy development/programming with Ruby on Rails 🙂

Setup Scheduled Jobs with Sidekiq, Redis & Ruby on Rails

Sidekiq has been my favorite tool for setting up background processing in Ruby on Rails applications. Mainly I use it for delivering emails, update data inside tables & much more… and it can take a little effort to get up and running every day in exact time on i.e. Heroku.

I have worked with Heroku Scheduler jobs but I have found some issues which explained there documentation that’s why I’m using Sidekiq Scheduler.

Follow below steps:


gem install sidekiq-scheduler

or you can use your Gemfile
# sidekiq
gem 'sidekiq', '~> 3.3.0'
# sidekiq scheduler
gem 'sidekiq-scheduler', '~> 1'

Then create a folder inside app directory which name “workers”.


Create a file inside workers folder like “hello_world.rb”.

class HelloWorld
  include Sidekiq::worker
  def perform #=> you can write anything based on your action like 'send_email' or 'newslatter' etc ...
     puts 'Hello World'

Now you can go your config file config/sidekiq.yml

  every: 1m   # Runs once per minute
  class: HelloWorld

Then run

bundle exec sidekiq

Redis is required for sidekiq, install this on your Heroku app then past this on your Procfile same as below-

worker: bundle exec sidekiq -c 5 -v

Then push to your production.

Happy coding 🙂

Users Activity Tracking on Rails

How to enable users activity tracking using the public_activity gem?

On Rails, the public_activity provides easy way for tracking activity for ActiveRecord, Mongoid 3 and MongoMapper models. Simply we have to put records what has been changed or created and that will gives the ability to present those recorded activities to users. Following Github screenshot showing the expected output from the Rails users activity tracking-


Following steps we have to follow: (ActiveRecord only)

Step 1:

Add gem 'public_activity' on your Gemfile

Step 2:

Run bundle install

Step 3:

Run rails g public_activity:migration


Run rake db:migrate

Now let’s configure the Model

class Post < ActiveRecord::Base

include PublicActivity::Model




Custom activities

@post.create_activity key: 'post.commented_on', owner: current_user


View activities

#=> app/controller/notifications_controller.rb

def index

@activities = PublicActivity::Activity.all



That’s all for tracking all activities.

Happy coding 🙂