Nginx custom headers for a Unicorn Rails app

Recently I had to implement an API for a Rails app running on Unicorn being proxied in from Nginx. The problem I had was that my custom header wasn’t being passed through from Nginx.

I had already gone ahead and added to my location directive

proxy_set_header        X_SESSION_KEY $http_x_session_key;

But alas I still had problems. Turns out there’s little thing called “underscores_in_headers” which needs to be turned on for my custom (with underscores) API header to work.

Simply add it to your main nginx.conf after the http {

underscores_in_headers on;

RVM – no such file to load — openssl

Installed ruby 1.9.2 via RVM and getting the following error?

no such file to load -- openssl

Try getting RVM to install the required openssl files. Unfortunately this means removing ruby and installing it again.

rvm pkg install openssl
rvm remove 1.9.2
rvm install 1.9.2 --with-openssl-dir=$HOME/.rvm/usr

But hey, it works.

Running Resque Workers from Upstart + RVM

I recently had the task of getting resque workings to start from Ubuntu’s upstart daemon.

First I created a bash script with the following;


# Load RVM into the shell
source "$HOME/.rvm/scripts/rvm"

# Switch to the right RVM version
rvm 1.9.2

# CD to the rails app
cd /home/myapp/

# Start the resque workers
QUEUE=* /home/myapp/.rvm/gems/ruby-1.9.2-p180/bin/rake resque:work

Put the above contents in a file called in your home directory.
Then give it executable status!

chmod +x

Next, create a file called resque.conf in /etc/init (you’ll need sudo access).

description "my App resque workers
start on (net-device-up and local-filesystems)
stop on runlevel [016]
exec su -c "/home/myapp/" myappuser >> /home/myappuser/resque.log 2>&1

If you run into errors, you can take a peek at /home/myappuser/resque.log to debug the problem.

Good luck! :)

Valum Fileupload +jQuery +csrf

I recently went to implement Valum’s Fileupload script with a Ruby on Rails jQuery project I was working on.

One thing I figured out is that all requests in Rails3 must send also send the X-CSRF-Token. Now normally the rails.js jQuery adapter takes care of this; but Valum’s fileupload script is written in raw javascript :)

The problem I had was a logged in user was automatically logged out whenever they attempted a fileupload (I was using the Devise auth gem).

Find line 1203 and add the following below it.

        var token = $('meta[name="csrf-token"]').attr('content');
        if (token) xhr.setRequestHeader('X-CSRF-Token', token);

This will ensure that fileupload requests also send the csrf token.

SQL – Changing to British Datetime format

Error converting data type varchar to datetime
Are you getting the above error?

Run the following under your app user.

select @@Language, @@Langid

If it says us_english then you’re probably hitting errors when parsing dates as DD/MM/YYYY.
We can change the default language for a particular user. Login to your SQL server as an administrator account and run the following;


Then login with the user “yourapplogin” and run

select @@Language, @@Langid

Hopefully you now see “British” and 23.

Ruby On Rails AJAX File Upload With Valum

Some sample code I wrote with Andrew Valums’s AJAX uploader script and Ruby On Rails.

Note; I use the prototype javascript library to manipulate the DOM during the onComplete event.

If you need any help getting this to work, simply use the comments below.

  function createUploader(){            
      var uploader = new qq.FileUploader({
          allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'], 
          element: document.getElementById('file-uploader-demo1'),
          action: '/vendor/products/12/upload',
          params: {
                 postid: '9999'
          onComplete: function(id, fileName, responseJSON){
            if (responseJSON.success) {
              $$('.qq-upload-failed-text').first().update('Successfully Uploaded!');
              $$('.qq-upload-failed-text').first().update('Hmm .. upload failed');
  // in your app create uploader as soon as the DOM is ready
  // don't wait for the window to load  
  window.onload = createUploader;

and the ruby on rails code

  def upload
    @filename = params['qqfile']
    newf ='assets/' + @filename, "wb")
    str = 
    render :text => '{success:true}'

WordPress on Mobile (iPhone and Android)

WPTouch is a fantastic plugin for WordPress that allows your users to browse your WordPress Blog on iPhone and Android mobile phones.

If you want to customise the mobile theme, you can modify the PHP theme included in your wp-content/plugins/wptouch/themes folder in the same way as any other theme.

See a customised theme in action by visiting on your Android or iPhone.

rake db:seed | Don’t know how to build task error

So I ran into a little issue today, I wasn’t able to get my rake db:seed task to work. This is the error I was getting;

rake db:seed  don't know how to build task

The solution?

Update rails to 2.3.5


gem update rails

Ordinal Number in Reporting Services

Recently I had a client request for reporting services dates to use ordinal numbers, that being, “1st instead of 1, 2nd instead of 2″ etc. To my surprise, this isn’t a standard datetime format in reporting services!

So I set out to create my own ordinal function based on a C# version I found on the Internet.

To use the below function in your report;

1) Open up your report in Reporting Services
2) Make sure you’re in the Design section and click the “Report” menu option (up the top), then “Report Properties”
3) Select “Code”
4) Copy and Paste the function below into the “Custom Code” box.

Public Function FormatOrdinal(ByVal day As Integer) as String

    ' Starts a select case based on the odd/even of num
    Select Case (day Mod 100)
        ' If the nymber is 11,12 or 13 .. we want to add a "th" NOT a "st", "nd" or "rd"
        Case 11
        Case 12
        Case 13
            Return day.ToString() + "th"
    End Select

    ' Start a new select case for the rest of the numbers
    Select Case day Mod 10
        Case 1
            ' The number is either 1 or 21 .. add a "st"
            Return day.ToString() + "st"
        Case 2
            ' The number is either a 2 or 22 .. add a "nd"
            Return day.ToString() + "nd"
        Case 3
            ' The number is either a 3 or 33 .. add a "rd"
            Return day.ToString() + "rd"
        Case Else
             ' Otherwise for everything else add a "Th"
            Return day.ToString() + "th"
    End Select
End Function

I was then able to use the function in an expression.

I wanted to format “01/01/2010″ as “1st January 2010″. My expression was;

=Code.FormatOrdinal(Day(Fields!LETTERDATE.value)) & " " & MonthName(Month(Fields!LETTERDATE.value), False) & " " & Year(Fields!LETTERDATE.value)

Will_paginate with multiple models

If you need to implement paging in your Ruby on Rails application, a quick and easy way is to use the fantastic “Will_Paginate” plugin (available here).

However I came across a need to paginate multiple models on the same page, for example; a list of users and a list of groups.

Luckily Google came to the rescue with this article, which demonstrates the use of the :page option, allowing you to specify the page against a model object.

Check out the code below (courtesay of


@users = User.paginate(:page => params[:user_page], :per_page => 10)
@administrators = Administrator.paginate(:page => params[:administrator_page], :per_page => 10)


<%= will_paginate @users, :param_name => 'user_page' %>
<%= will_paginate @administrators, :param_name => 'administrator_page' %>

Capistrano issues – no such file or directory

So I was playing around with my new Slicehost the other day and following their guides to automate a Ruby on Rails deployment process using capistrano.

For those that don’t know, capistrano comes as a ruby gem which allows you to completely automate tasks. In my case, I wanted to remotely tell my Ruby on Rails application to retrieve the latest version of the application from github (remote repository) and then restart my Rails app.

The documentation tells me that a simply “cap deploy” from the root of my rails folder should execute my capistrano script. However for hours upon hours I was banging my head against a wall.

Here’s the error I was receiving;

C:\Web\> cap deploy
* executing `deploy'
* executing `deploy:update'
** transaction: start
* executing `deploy:update_code'
updating the cached checkout on all servers
executing locally: "git ls-remote master"
*** [deploy:update_code] rolling back
* executing "rm -rf /home/xxxx/public_html/releases/20100222103818; true"
servers: [""]
[] executing command
command finished
C:/Apps/Ruby/lib/ruby/gems/1.8/gems/capistrano-2.5.16/lib/capistrano/recipes/deploy.rb:98:in ``': No such file or direct
ory - git ls-remote master (Errno::ENOENT)

The solution

Ok so I’m not really going to call this a solution because I don’t know why this works (and maybe one of you can assist me in this) but running the command “cap deploy” under a MINGW32 command shell instead of the usual Windows command prompt seemed to work just fine.

(I just MINGW32 as a shell to run all my GIT repository commands)

If you don’t use Git on windows or you don’t have MINGW32 installed, I suggest you have a look at this Git on Windows page.

How to fetch Last Record in Subsonic

Is it just me or is Subsonic the topic of discussion right now? :D
I had a need to retrieve the last ID that had been generated in a table; that being, the last “auto increment” ID of a table.

The following example worked a charm using Subsonic and activerecord.

var fetch_ref_id = contract.All().OrderByDescending(c =>;
if (iRef_new_id != null)
     iRef_new_id = fetch_ref_id[0].id;

As you can see, it creates a new list (noted by the ToList()) by connecting to the table “category”, it then selects all results (All()) and then orders the list by Descending and finally, the take(1) simply takes the top record.

I then whack the result (if you have a column called id) into a integer.

« Previous Entries