Multiple model search in rails with solr

lrSearching is much easier if you use solr or elastic search, no need to write complex database queries.

If you want to integrate solr with your rails application means there is a gem available

Add to Gemfile:

gem 'sunspot_rails'
gem 'sunspot_solr' # optional pre-packaged Solr distribution for use in development

Bundle it!

bundle install

Generate a default configuration file:

rails generate sunspot_rails:install

If sunspot_solr was installed, start the packaged Solr distribution with:

 bundle exec rake sunspot:solr:start

Then add the following code in model file which you going to search

searchable do
  text :<field_name>

In your controller queries

@search = Project.solr_search do
fulltext params[:search]
@projects = @search.results

Thats all, if you pass search params from your view file, then solr will give you the relevant projects.

Now I will show you how to search multi models in same querie,

simply add the same

searchable do
 text :<field_name>

In model files which you need to search, Then in your controller

@search =,Comment, File) do |s|

@result = @search.result

will give you the result from project, file and comment models


Run Sinatra along with Rails

Sinatra is much better than rails for writing API codes and small functionalities, We can run sinatra app inside rails application.

Write your sinatra codes inside library folder of rails application, you can call rails application database tables from sinatra app also.

Then on your rails app

# This file is used by Rack-based servers to start the application.

require ::File.expand_path(‘../config/environment’, __FILE__)

require_relative ‘lib/api’

map ‘/api’ do

map ‘/’ do
run Rails.application

Put this code, so normal request goes to rails controller and  request url with /api goes to sinatra app. This way we can use both rails app and sinatra app together.


Easy Ruby on Rails install

Whenever I setup new Linux for developing rails application. I feel bit tired of installing all necessary things for rails development.

For that I have written one shell script, that install most of the things requires for rails development. If you want this lazy thing. You can check here

And use it , fork the code and update if you feel some thing to be added.


SOA – Service Oriented Architecture for Dummies

SOA –  Service Oriented Architecture

  What is SOA?

before going to SOA you need to know about what is service in web. Service is a bit of code (say so) that get the input  data which you have given and process it and give the resultant data in any format (most probably XML,JSON). The service can be written in any language(java, ruby, etc..).

If you take web application there mostly two kind of design patterns monolithic architecture and service oriented architecture.

Now consider a banking application, if its a monolithic architecture then entire process like log in, account details, money transfer, loan application are done in same server.

If its a SOA then each module is run in different server and they communicate with each other. And the customer views the collected details from all the servers.


 Where we use SOA?

If its enterprise level application, it requires API module to be implemented,there are many number of modules to be implemented in application, Needs to use different programming languages together then its better to implement SOA.

Advantages of using SOA

1. Development made easy – if there is a fresh developer comes to project, he don’t want to go through entire project. He can start to work with a service.

2.Platform independent- In SOA you can use any language you want  you can use java in one service and ruby in another service means also they can communicate with each other. So you don’t need particular language developer for developing.Then parallel development made easy.

3. Re-usability – Each service runs independently so you can use any service any where.

4.Higher availability – As previously said each service runs independently , if any service failures that part of the application only stops to work. So our web application is probably always available.

5. Cost Reduction – Definitely it will reduce the initial and maintenance cost if its a big and high scalability application


1. Complex structure – Since each service placed in different place, you have  make a mechanism to communicate each service together.

2. Data – We cannot transfer large data from one service to another service, mostly the services communicate by using http request so we can send a small amount of data only.

3. Cost – If its small application , if you use SOA then it will increase the maintenance cost because it uses many servers and we have maintain many servers.

Making the environment for developing android application in Ubuntu

Hi all,

Its better to have IDE for creating android application rather than using stand alone SDK . I have choosen andorid studio as IDE because it will be the official IDE by few months as android says.

First you need to download android SDK before installing android studio get it from here

After downloading unzip the archive and keep as its in a folder

Open a terminal window.

Type the following comments

  • sudo apt-add-repository ppa:paolorotolo/android-studio
  • sudo apt-get update
  • sudo apt-get install android-studio

after installing android studio

open terminal and go to the android studio folder. Probably in opt/android_studio

  • cd opt/android_studio/bin
  • ./

now your android studio will starts in menu go to

configure -> project defaults ->  Project structure and then select the folder where you extracted the SDK , If you need install some additional packages prompt by android studio

then your ready to go with creating application by selecting new project , and for first time android studio will download and install some additional packages, sdk

Now you are ready to hit the android world 🙂

My new gem – label_better_rails

Hi after a success of my previous gem sticky-rails ( gemmified version of sticky jquery plug-in)  , I have created another gem and this also a gemmified version of another beautiful jquery plug-in label_better ,
This will help you to add label_better gem to your rails application assets pipeline quickly , Home page for this gem is

Thanks to

Label your form input like a boss with beautiful animation and without taking up space

Screen shot


Add this line to your application’s Gemfile:

gem 'label_better_rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install label_better_rails

label_better is a jquery_plug in that gives beautiful animation to your label , so please check if you are using the jquery on your rails app, and add jquery.label_better in your application.js

Your app/assets/javascripts/application.js appear like:

//= require jquery
//= require jquery_ujs
//= require jquery.label_better
//= require_tree .

Then in your view file where you want to add label_better just remove our default rails label then give a class name and the placeholder to the field example

    <%= f.text_field :firstname ,:class => 'label_better', :placeholder => 'firstname'%><br/><br/>
    <%= f.text_field :lastname ,:class => 'label_better', :placeholder => 'lastname'%><br/><br/>
    <%= f.email_field :email,:class => 'label_better', :placeholder => 'email' %><br/><br/>
    <%= f.phone_field :phonenumber,:class => 'label_better', :placeholder => 'Mobile' %><br/><br/>
    <%= f.url_field :website ,:class => 'label_better', :placeholder => 'Website'%><br/><br/>
    <%= f.password_field :password ,:class => 'label_better', :placeholder => 'confirmpassword'%><br/><br/>
    <%= f.password_field :confirmpassword , :class => 'label_better', :placeholder => 'confirmpassword' %>

then add javascript in your view file

    position: "top", 
    animationTime: 500, 
    easing: "ease-in-out",
    offset: 5, 
    hidePlaceholderOnFocus: true 

Change this values depends on your need


  1. Fork it ([my-github-username]/label_better_rails/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Collection Of Database Queries in Rails

Retrieving a Single Object

client = Client.find(10)

client = Client.take

client = Client.first

client = Client.last

Client.find_by first_name: ‘Lifo’

Client.where(first_name: ‘Lifo’).take

Client.find_by! first_name: ‘Lifo’

Retrieving Multiple Objects

client = Client.find([1, 10])




Retrieving Multiple Objects in Batches

User.all.each do |user|




Pure String Conditions

Client.where(“orders_count = ‘2’”)

Client.where(“orders_count = ?”, params[:orders])

Client.where(“orders_count = ?”, params[:orders])

Client.where(“orders_count = #{params[:orders]}”)

Client.where(orders_count: [1,3,5])

Post.where.not(author: author)



# OR


Selecting Specific Fields

Limit and Offset



Group“date(created_at) as ordered_date, sum(price) as total_price”).group(“date(created_at)”)

Having“date(created_at) as ordered_date, sum(price) as total_price”).

 group(“date(created_at)”).having(“sum(price) > ?”, 100)

Overriding Conditions

Post.where(‘id > 10’).limit(20).order(‘id asc’).except(:order)

Post.where(‘id > 10’).limit(20).order(‘id desc’).only(:order, :where)

Client.where(“orders_count > 10”).order(:name).reverse_order

Null Relation


Readonly Objects

client = Client.readonly.first

client.visits += 1

Optimistic Locking

c1 = Client.find(1)

c2 = Client.find(1)

c1.first_name = “Michael” = “should fail” # Raises an ActiveRecord::StaleObjectError

Find or Build a New Object


Client.find_or_create_by(first_name: ‘Andy’)


The find_or_initialize_by method will work just like find_or_create_by but it will call new instead of create. This means that a new model instance will be created in memory but won’t be saved to the database. Continuing with the find_or_create_by example, we now want the client named ‘Nick’:

Finding by SQL

Client.find_by_sql(“SELECT * FROM clients

 INNER JOIN orders ON = orders.client_id

 ORDER BY clients.created_at desc”)

Existence of Objects




Client.where(first_name: ‘Ryan’).count

Client.includes(“orders”).where(first_name: ‘Ryan’, orders: { status: ‘received’ }).count





Form Helpers

<%= form_tag do %>

A Generic Search Form

<%= form_tag(“/search”, method: “get”) do %>

 <%= label_tag(:q, “Search for:”) %>

 <%= text_field_tag(:q) %>

 <%= submit_tag(“Search”) %>

<% end %>


<%= check_box_tag(:pet_dog) %>

<%= label_tag(:pet_dog, “I own a dog”) %>

<%= check_box_tag(:pet_cat) %>

<%= label_tag(:pet_cat, “I own a cat”) %>

Radio Buttons

<%= radio_button_tag(:age, “child”) %>

<%= label_tag(:age_child, “I am younger than 21”) %>

<%= radio_button_tag(:age, “adult”) %>

<%= label_tag(:age_adult, “I’m over 21”) %>


<%= text_area_tag(:message, “Hi, nice site”, size: “24×6”) %>

<%= password_field_tag(:password) %>

<%= hidden_field_tag(:parent_id, “5”) %>

<%= search_field(:user, :name) %>

<%= telephone_field(:user, :phone) %>

<%= date_field(:user, :born_on) %>

<%= datetime_field(:user, :meeting_time) %>

<%= datetime_local_field(:user, :graduation_day) %>

<%= month_field(:user, :birthday_month) %>

<%= week_field(:user, :birthday_week) %>

<%= url_field(:user, :homepage) %>

<%= email_field(:user, :address) %>

<%= color_field(:user, :favorite_color) %>

<%= time_field(:task, :started_at) %>

<%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %>

<%= range_field(:product, :discount, in: 1..100) %>

The Select and Option Tags

<%= select_tag(:city_id, ‘<option value=”1″>Lisbon</option>…’) %>

TIme zone

<%= time_zone_select(:person, :time_zone) %>

Country select

Using Date and Time Form

<%= select_date, prefix: :start_date %>

<%= select_year(2009) %>

<%= select_year( %>

Uploading Files

<%= f.file_field :picture %>

layout helpers

<%= javascript_include_tag “main”, “columns” %>

<%= stylesheet_link_tag “” %>

<%= image_tag “header.png” %>

<%= video_tag “movie.ogg” %>

<%= audio_tag “music.mp3” %>