Custom Layout for Devise

Custom Layout in Devise, devise is an awesome gem that provides the quick and easy way for the rails app to have user authentication.

But you may be face with the need to add a custom layout to devise. There’s a couple of ways of doing so, but today I am going with the easiest way without bloating your codes.

In Application.rb in config, add the following section.

config.to_prepare do
Devise::RegistrationsController.layout "conversation"

This will apply the conversation layout to the Devise::RegistrationsController.

You will need to have the conversation.html.erb layout in the appviewslayouts folder.

Visit the following article to understand more on the layouts

Layout in Ruby on Rails


Layout in ruby on rails provide the flexibility to allow different views to come together and render as a page. Think iFrame but we without the cross-domain issue.

Layout are located in your project, appviewslayouts, by default you will only have application.html.erb

Layout will always have the  <%= yield %> tag, this will render the current controller/action.

What is this important?

Imagine this, you have a Landing Page for public users to visit the application and now you have a Dashboard Page where the users sign in.

These two pages will have different layout for sure. You will also want to ability to maintain them separately and maybe reuse some of the codes that you have developed as part of the project.

How do I then do it?

Taking the example above, say you have a Landing Page and a Dashboard page.

You will also have the controllers for them HomeController and DashboardController respectively.

Within the respective controller, after the class declaration, the first line end the following code

layout “public”

public will be the name of your layout file in the appviewslayouts folder.

application.html.erb is the default that will be applied to the rest without any additional setting.

Sample of the Layout for HomeController.

class HomeController < ApplicationController
layout "public"

WildCard Search in Ruby on Rails

Wildcard Search

Assuming that you have you have the following model:

Model : Book


  • BookName
  • Author
  • PublishedDate
  • Edition

Typical, when you try to do a wildcard search you will do the following code below:

Book.where(“BookName LIKE ‘%#{BookNameInput}%’)

The above returns the following in terms of SQL ->

SELECT “Books”.* FROM “Books” WHERE (BookName LIKE ‘%BookNameInput%’)


This makes you vulnerable to SQL Injection, for more information visit,


Use the following syntax instead:

Book.where(“BookName LIKE (?)” , “%#{BookNameInput}%”)

Additional information:

If you want to do WILDCARD SEARCH and ignoring case sensitivity, use iLIKE instead of LIKE.



Redirect After OmniAuth Sign in With Devise

class AuthenticationsController < ApplicationController def create auth = request.env[“omniauth.auth”] user = User.find_by_provider_and_uid(auth[“provider”], auth[“uid”]) || User.create_with_omniauth(auth) sign_in_and_redirect(:user, user)

end end


Add the line in bold to redirect!

OmniAuth & Devise: Validation failed email and password cannot be blank

If you are using Devise as the authentication for your Ruby On Rails application and you are looking to implement OmniAuth, that allow the users to login with their Facebook or Google Account.

But once you have all the codes and omniauth setup, on creation you will hit the following error:

Validation Failed: Email and Password cannot be blank. Background

The issue here is that the Devise model that you are working with will have the following :validatable added as part of the model. This is to validate that the database authentication have both the email and password before creation of the account.

But with omniauth, we may not get the email or do the user need the password to login, they simply use the relevant account for the different providers, such as Twitter, Facebook or Google to login.


We will need to overwrite the default Devise validation. Using the following methods below. Just copy them to your model and you should be good.


def email_required? super && provider.blank? end def password_required? super && provider.blank? end


Note : provider is a field or column in your model.

Validation failed: Password can’t be blank

Ruby on Rails : preloading data or Loading Massive amount of data

To load data via Ruby On Rails:

1. Create this a file name “import.rake” in the following location: App -> Lib -> Tasks

2. Place your CSV file in the following location: Public -> SeedData (create this folder)

2. This are the codes that should be in the import.rake files, note that the row[1] is corresponding to the CSV column


require ‘csv’

desc “Import a CSV file into Active Record”

task: import => [:environment] do

CSV.foreach(‘public/seeddata/Sample Data.csv’, :headers => false) do |row|
<<Replace this with your model name>>.create( :fullname => row[1], :currency =>row[3])



Rails 4: Dynamic populate field value

I was playing around with Ruby on Rails (RoR) over the weekend and I wanted to populate some textfield on the form base on a certain dropdown list selection. After a couple of hours of research, I managed to piece together how it will work in RoR and I decided to share it here for everyone else who are hunting for the information.

Assuming you have a form, with a dropdownlist and 2 textfields with the selection of the dropdownlist you are going to populate the textfields with the corresponding values.

Step 1: Finding out the ID for the forms elements.
I will ask you to view source on your page and take note of the respective elements. In my case they are as follows:
– Dropdownlist : counter_cid
– Textfield 1 : price_input
– Textfield 2 : date_input

Step 2: Using Ajax & Jquery
Add the following into your View page.

In the script, I basically say on the dropdownlist on change, I will call Ajax to the following URL (i will get to this in Step 4) and the data is the value of the dropdownlist selected. Finally, I tell it that this is a script return type.
<% content_for :bodyJS do %>

<script language=”javascript”>
$(document).ready(function() { $(‘#counter_cid’).change(function(){ $.ajax({url: ‘/counters/currentprice’, data: ‘id=’ + $(‘#counter_cid’).val(), dataType: ‘script’}); }) });
 <% end %>

Step 3: Adding the Method to your Controller file

In your controller file, my case CounterController.rb, insert the following:

This will tell the controller to response to the following format, add this line as the first line in the controller class.

respond_to :html,js

Second, we going to define the method.

def currentprice()
name = Counter.find(params[:id]).name
quote = StockQuote::Stock.quote(name)
@currentprice =

Step 4: Routes.rb
Now we need to configure the routes so that the ajax call could access.

Change your routes to the following:

resources :counters do
collection do
get "currentprice"

After you are done, do a rake routes in your terminal to verfiy that is created.

Step 5: Finally adding in the js.erb file.
This will help us update the value back to the texfield

Browse to the counter folder under App-> Views -> Counter -> Add a new file “currentprice.js.erb”

$("#price_Input").val(<%= @currentprice %>);

Finally you are good to go!

Bootstrap Theme : Bootswatch

Bootswatch ; free theme

To leverage that we have a gem that is designed to do just that.

Add the following in your Gemfile

 gem 'bootswatch-rails'

Do a bundle install

 bundle install 

Browse to the following folder, app/stylesheets/application.css.scss

 @import 'bootswatch/simplex/variables'; 
 @import "bootswatch/simplex/bootswatch" 

Now test to see if this works. if you are looking to change the theme, just replace simplex with the name of the theme from Bootswatch.

Bootstrap-sass on Existing Ruby on rails project

The twitter-bootstrap gem provide a nice set of design template for all programmer out there and allow for more time to be devoted in the functionality instead of design.

Setting up the Bootstrap-sass from thomas macdonald. Shoutout to his github url for the project

Step 1: Setup the GemFile

gem 'sass-rails'
gem 'bootstrap-sass'

Step 2: Bundle Install

do a bundle install from the terminal.

bundle install

Step 3: application.js

Locate the following file app/assets/javascripts/application.js

Add the following line above the /= require_tree,

/= require bootstrap

Step 4: application.css

Locate the following file app/assets/stylesheets/application.css

Add the following line in the application.css file

@import "bootstrap";

Save the file as application.css.scss

Step 5: Done

We are now good to go.