Pagination in Ruby On Rails using will_paginate plugin

We do pagination in Rails by using its built in paginate method in our controller

def display_data
@display_data_pages, @display_data = paginate(:location_data,
:conditions => ["loc.updated_at < ?", params[:date]],
:joins => "as loc inner join location_address as locadd on ="
:per_page => 10,
:order => "location_name")

Often we would like to put this code inside our model mainly for two reasons:
1) Code Reuse, and
2) To keep the business logic where it belongs
But we couldn’t do that (since it is difficult to do) due to the paginate method and had to write the same code more than once in the controller and sometimes in more than one controller.
On top of that we have to put this chunk of code in our views only to show the pagination links
<div class="pagination">
<%= if @survdefault_pages.current.previous
link_to("< Prev", { :page => @survdefault_pages.current.previous })
end %>

<%= pagination_links(@survdefault_pages) %>

<%= if
link_to("Next >", { :page =>})
end %>

We can put this code inside a partial but it is still a pain.

Moreover, Rails’ built in pagination will be out of Rails before it will reach version 2 which is not that far.

Update: Rails built in pagination is now removed but is still available as a plugin, ie, classic_pagination.

We have another option, use will_paginate plugin. The advantages of will_paginate plugin are:
1) Easy to use,
2) Less code in views to show pagination links, and
3) It can be used inside models

Follow these steps to use will_paginate plugin

1) Grab it, by going to the command prompt and change directory to the app root. Then run
ruby script/plugin install svn://
NOTE If the above code doesn’t installs the plugin in your vendor/plugins directory then you probably don’t have svn installed on your machine.

2) Now in our controller we can simply write

def display_data
@display_data = LocationData.paginate(:page => params[:page],
:conditions => ["loc.updated_at < ?", params[:date]],
:joins => "as loc inner join location_address as locadd on =", :per_page => 10,
:order => "location_name")

:per_page and :page are required.
The best thing is, as mentioned above, we can move this code to the LocationData model that will help in keeping our controller clean and will also help in code reuse.
To do that, we can create a class method in our model like:

def self.display_location_data(update_date, page)
paginate(:page => page, :conditions => ["loc.updated_at < ?", update_date], :joins => "as loc inner join location_address as locadd on =",
:per_page => 10,
:order => "location_name")

In our controller, the display_data method will now be replaced with just one line

def display_data
@display_data = LocationData.display_location_data(params[:date], params[:page])

In the view, the big chunk of code will be replaced by a single line to show our pagination links, like

<%= will_paginate @display_data %>

And we are done…

UPDATE: Formatting / Styling pagination links

Getting a random line from a file – and a question!!!

line = IO.readlines('some_file')
c = rand*line.length.to_i
puts line[c-1]

Very simple logic and it can be easily understood by just looking at the code itself. No explanation needed. If someone knows a better way to do it then please post it in the comments. BTW..thats in ruby.

How to get acts_as_attachement plugin working on mac osx

If you want to use acts as attachement for image upload/manipulation as well then first you need to install imagemagick (and its dependencies) and RMagick.

Before installing imagemagick you also need to install the following libraries as well:

1) libjpeg

Download it from

tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b
cp /usr/share/libtool/config.sub .
cp /usr/share/libtool/config.guess .
./configure --enable-shared --enable-static
sudo make install
sudo ranlib /usr/local/lib/libjpeg.a

2) libpng

Download it from

tar zxvf libpng-1.2.22.tar.gz
cd libpng*
make check
sudo make install
sudo ranlib /usr/local/lib/libpng.a

3) freetype

Download it from

tar zxvf freetype-2.3.5.tar.gz
cd freetype*
sudo make install

4) libwmf

Download it from

tar zxvf libwmf-0.2.8.tar.gz
cd libwmf*
make check
sudo make install

5) ghostscript

Download it from

tar zxvf ghostscript-8.01.tar.gz
cd ghostscript*
sudo make install

Imagemagick installation
Download it from

tar zxvf Imagemagick-6.3.2.tar.gz

cd Imagemag*
export CPPFLAGS=-I/opt/local/include
export LDFLAGS=-L/opt/local/lib
./configure –prefix=/opt/local –disable-static –with-modules –without-perl \
–without-magick-plus-plus –with-quantum-depth=8 \
sudo make install

RMagick Installation
If ruby and gem package manager is installed on your machine then simply do
sudo gem install rmagick
To check whether it is installed properly;
– go to terminal and run
irb -rubygems -r RMagick
irb(main):001:0> puts Magick::Long_version

this should give you the following output

This is RMagick 1.15.10 ($Date: 2007/06/09 16:45:25 $) Copyright (C) 2007 by Timothy P. Hunter
Built with ImageMagick 6.3.2 10/28/07 Q8
Built for ruby 1.8.6 (2006-12-25 patchlevel 0) [i686-darwin8.9.1]]
Web page:

Installing rmagick from source

tar xvzf RMagick.tar.gz
cd RMagick*
sudo make install

Using Act_as_attachment
I was about to write this but then I found a very good tutorial on installing and using acts_as_attachment here.

Full text search using Ferret (acts_as_ferret) with rails

I recently started working with acts_as_ferret so I thought to put together a little how to:

Assuming you already have ruby on rails environment set up

1) To install it run gem install ferret
this will prompt you to select a gem for your platform

2) go to your rails project root directory and run
script/plugin install svn://

3) Add require 'acts_as_ferret' to your config/environment.rb

4) Resart your app

To add full text search capability to a model simply add this within your model


To add full text search capability to a model but on some specific attributes/field_names add this

acts_as_ferret :fields => [ :author, :content ]

How to perform search?

If your model name is location then you can use


Note: If you have very large number of records then it might take a while to run your search for the first time as it indexes all the records

If you want to use pagination or multiple models then use
Location.find_with_ferret query, :page => params[:page], :per_page => 10,
:multi => [ Model_2, Model_3 ]

I will be adding some advanced stuff later on …

How to get Gruff working with Rails on windows

NOTE: You can’t do gem install rmagick on windows since (as of now) rmagick gem is only for *nix systems

1) Download rmagick-win32 from

This also has imagemagick for 8 pixels so you don’t need to do a separate download for imagemagick. If you want imagemagick for 16 pixels then download it from here

Imagemagick site says ’16 bitversion permits you to read or write 16-bit images without losing precision but requires twice as much resources as the Q8 version.’

3) Install Imagemagick

To confirm if imagemagick is installed properly go to your command prompt and type

convert logo: logo.gif
identify logo.gif
imdisplay logo.gif

this should display the imagemagick logo if everything was ok

4) Go to your command prompt and run gem update --system

5) Go the directory where you unzipped the downloaded rmagick-win32 file

6) Run gem install rmagick --local

after it is installed successfully then you should see

Successfully installed rmagick, version 1.15.9

7) Either run gem install gruff


to use rails plugin. Go to your app root directory and run

ruby script/plugin install

And you are done…

Not following Rails table and field conventions

Whenever we generate a model then Rails expects that the underlying table has following:

1) table name starts with small letter and the word is in plural (ie, customers)

2) a table name that has more than one word in its name then it should be separated by an underscore (ie, line_items)

3) the field names with in the table should also start with small letters.

4) the primary key of the table should be an auto-incremented, integer type and with field name id

5) if you have a foreign key with in that table then it should be in the form table_name_id

If a table follows all the above conventions then the generated model will work straightaway. Otherwise follow these steps

  • If you are not following the conventions 1 & 2 and your table name is something like CustomerRecord instead of customer_records then you have to set the table name within your model just after the class name, like this:

class Customer < ActiveRecord::Base

set_table_name “CustomerRecord”



  • If you are not following the convention 4 and your auto-incremented primary key is called Customer_ID instead of id, then do this

class Customer < ActiveRecord::Base

set_primary_key “Customer_ID”



  • If you are not following convention 5 and your foreign key is named as Customer_Category, then you have to specify that in your model relationship,

class Customer < ActiveRecord::Base

set_table_name “CustomerRecord”

set_primary_key “Customer_ID”

belongs_to :category, :foreign_key => ‘Customer_Category’



How to install Ruby on Rails with Sybase anywhere adapter on Windows

Installing Rails on Windows and using Sybase as db for the first time is a pain. So I thought to write a how to:

1) Download latest stable release of Ruby from on to your computer.

2) Run the executable and follow the onscreen instructions.

3) Once Ruby is installed successfully then go to command prompt and type ruby -v then hit enter. If everything was done properly then you will see the version of ruby, something like this

ruby 1.8.6 (date ...) [..]

4) Now you need to download the latest gem from

5) Unzip it and then go to the command prompt again and type ruby setup.rb.

6) This will install the gem package manager. To be sure if everything went OK type gem -v on the command prompt to see the version of gem installed on your machine.

7) Now, to install rails run gem install rails --include-dependencies and wait while it is installed.

8) Once this process is complete then run rails -v and you should get the rails version as the output.

To communicate your rails app with Sybase you need to follow these steps.

1) Download file (by Michael Scott)

2) Inside you have two ruby files and a read me file:

  • Put sybaseanywhere_adapter.rb file under your ruby installation, i.e., ruby\lib\ruby\gems\1.8\gems\activerecord-1.13.2\lib\active_record\connection_adapters
  • Put sybaseanywhere.rb file file under your ruby installation, i.e., ruby\lib\ruby\gems\1.8\gems\activerecord-1.13.2\lib\active_record\vendor
  • Now add sybaseanywhere in ruby\lib\ruby\gems\1.8\gems\activerecord-1.13.2\lib\active_record.rb file like this
    RAILS_CONNECTION_ADAPTERS = %w( mysql postgresql sqlite firebird sqlserver db2 oracle sybase openbase frontbase sybaseanywhere )

3) Now create a directory called ADO, if you don’t already have it under your ruby installation directory, for example, ruby\lib\ruby\site_ruby\1.8\DBD

4) Download rub-dbi package from unzip it and put the ruby-dbi\lib\dbd\ADO.rb under your newly created directory ruby\lib\ruby\site_ruby\1.8\DBD\ADO

5) Your database.yml will also look a bit different like this

adapter: sybaseanywhere
dsn: dsn_name
mode: DBI:ADO

Obviously, you have to create your dsn name using windows control panel. Now thats something off topic and I imagine you already know how to do this.

On windows you can use Aptana as your IDE (download from here) since it is free and has plugins for rails, svn, etc.

SP| launch

SP| is launched partially on 06/10/2007.

As I said in my earlier post that I will work on the idea but launching it within two days, yes … that’s quick.

I intend to not promote it for quite some time because I need to implement a few important things which forms the core of SP|hred. So if you stumble upon SP| in coming weeks then you are probably one of the first users of SP|hred.

Spread It or Shred It is born while I was attending fowa and I am not sure yet whether its a good or bad idea but I am gonna work on it and try to keep it simple.

I created a rough architecture of the site during one of the presentation at future of web apps conference on fowa brochure (Sorry Ryan Carson…I just didnt carry enough paper with me).

I thought about the idea and then booked the domain last night itself, even started working on it.

Will talk later about what the site is actually about… 😉


I am currently attending the Future of Web Apps Conference in London and really excited about the kind of technologies google, yahoo and other companies are bringing.

I would really love to experiment with fireagle and also signed up for their alpha release.

If I get some time then I would love to play with Adobe AIR as well.

Lots of interesting people with lots of ideas and yes some cool start ups as well.

I met with Paul Graham of YCombinator and talked with him about an idea I have for some time.