Autocomplete fields in Rails 3.1 with JQuery-UI pt. 2

As i have written in my previous post, i’m playing with autocompletion in my web app. I have found some new tricks, that will speed up the process. Never liked the find_by_name implementation, but as this example is derived from jquery.autocomplete plugin behavior, i had no other way. Did some more exploring today and here is what i found out.
Because you are using json response on the ajax controller, and JQuery-UI autocomplete handles it perfectly, you can create a hidden field, and put the user_id there, so you have one less request to the database whena you are saving your record.
The improved model:

class Post < ActiveRecord::Base belongs_to :user attr_accessor :user_name def user_name if user_id end end [/ruby] And the part in your view that i left out the last time, but this one is just better in my opinion: [html] < %= f.label :user_name %>
< %= f.text_field :user_name %>
< %= f.hidden_field :user_id %>
Also, you have to edit the CoffeScript that does the magic for you, so it will return the id into the hidden field:

$(document).ready ->
    source: "/ajax/users"
    select: (event,ui) ->

An easier way of doing it, and leaner on the database queries, at least one less.

Autocomplete fields in Rails 3.1 with JQuery-UI

Almost every time you create a web application you will have to add at least one autocomplete field in your application. Here is one of the possible ways of doing it. I will be using Rails 3.1.beta1, JQuery-UI and CoffeScript to make it happen.

I have two models in my app, post(title, body) and user(name, email) and i want to select user with autocomplete when creating the post. As a prerequisite, i have created 100 users with Faker gem.

First, you have to add JQuery-UI to your app/assets/javascripts/application.js file so it will look like this:

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require_tree .

Next, we set up an ajax controller with rails g controller ajax users to have a controller with users action and automatic route. I like to call the controller ajax, or autocomplete, to keep things organized for this. Here is the ajax controller with everything just rendered into json that suits JQuery-UI autocomplete format

class AjaxController < ApplicationController
  def users
    if params[:term]
      like= "%".concat(params[:term].concat("%"))
      users = User.where("name like ?", like)
      users = User.all
    list = {|u| Hash[ id:, label:, name:]}
    render json: list

Next we set up the post model with user_name attribute getter and setter

def user_name=(name)
  user = User.find_by_name(name)
  if user
    self.user_id =
    errors[:user_name] << "Invalid name entered"
def user_name
  User.find(user_id).name if user_id

After this, it’s all CoffeScript which i add to app/assets/javascripts/

$(document).ready ->
  $('#post_user_name').autocomplete({source: "/ajax/users"})

And that is everything needed for a nice autocomplete, be sure to include a suitable JQuery-UI theme in your vendor/assets/stylesheets folder.

Rails 3.1 beta on Ubuntu

As i have written before, i use Ubuntu for my rails development, and have been using it as my main OS last 10 months. I have been trying all the rails 3.1 beta hype and encountered a problem running 3.1 apps on my machine.

The main problem is with CoffeScript and its compiling into “real” JavaScript. So here is an easy way to enable your machine for rails 3.1. You have to install Node.js on your machine( i have tried all other Javascript runtimes with no luck). All the instructions for other platforms are listed on the project’s GitHub page, i will include only the ubuntu procedure here.

sudo apt-get install python-software-properties

sudo add-apt-repository ppa:jerome-etienne/neoip

sudo apt-get update

sudo apt-get install nodejs

And that is all, hope i have made your life easier at least a bit.

Moving to WordPress

I just moved my blog from DasBlog to WordPress. The main reason for this was the expiration of my Win hosting account, and me phasing  my development to opensource.

I used DasBlog to BlogML converter for the conversion of posts, you have to download the whole folder and then point the tool at it.

After that, I installed BlogML Importer plugin for WordPress, and used that in the import script. I’m very happy that the process worked like a charm.

Now that everything works again, I can dedicate myself to my new love, Ruby and Rails development.

Installing Rails 3 in Ubuntu 10.04

As i am exploring different languages and platforms for web development, i have encountered(a few months ago) ruby on rails. I has impressed me so much that i wanted to create a virtual development environment for it. For the base i choose Ubuntu 10.04 LTS which is a great distribution for *nix beginners. We will install everything we need for a slick and updateable ruby on rails development machine.

I will just copy/paste the script i have made, notice that git version may change.

#Install git

#   1.  First we install the dependent packages, thus you wont have to install #   the packages yourself.

sudo aptitude build-dep git-core

#   2. Download latest stable GIT release from here


#   3. Extract the archive and change to the extracted directory

tar xvzf git-1.7.2.tar.gz
cd git-1.7.2/

#   4. Run the following

./configure && make
sudo make install

#5. Check installation and clean up

git --version
cd ../;rm -r git-1.7.2 git-1.7.2.tar.gz

#install curl
sudo apt-get install curl

#install rvm

bash < <( curl )

#Then add this line as the last line in your .bashrc:

if [[ -s "$HOME/.rvm/scripts/rvm" ]]  ; then source "$HOME/.rvm/scripts/rvm" ; fi

#install rvm dependencies

sudo apt-get install bison build-essential zlib1g zlib1g-dev libssl-dev     libreadline5-dev libreadline6-dev libxml2-dev git-core subversion         autoconf

#install ruby
rvm update
rvm install 1.9.2
rvm 1.9.2 --default
#test ruby version
ruby -v
# install rails 3.0.4
gem install rails

gem update --system
gem update

This is for a single user installation, like you would have at your home/work computer, for a server installation, you should install rvm as superuser so it will install rvm into /user/local/rvm

EDIT: There is an easier way to do this, as described on: Rails Ready

It is an automated script that does all of this for you

Moving oracle tables with lob columns to another tablespace

I have encountered a problem with oracle database that it does not reuse lob data. So, if you have 5000 rows of some lob data, and you delete them from the table, then insert the same 5000 rows, you will have 10000 rows of consumed space. That could be done easily with shrinking the table but the default tablespace segment space management (SSM) on oracle 10g is manual, so it does not allow row movement and table shrinking.

First, you create a tablespace with ASSM, that is automatic segment space management:

'/home/oracle/product/10.2.0/db_1/dbs/new_tablespace.dbf' SIZE 16109M AUTOEXTEND ON NEXT

Now we can proceed with table movement and after that lob_segment movement. There are some steps we should follow:

  1. Move table
  2. Rebuild indexes (and move them to the new tablespace if you wish so)
  3. Move the lob segment
  4. Enable row movement
  5. Shrink the table and lob segment

Here is the sql needed, of course, you will need to change and/or add indexes that reside on the current table.

--moving the table to the new tablespace
alter table table_name move tablespace new_tablespace;

--rebuilding the index(es) and moving them to the new tablespace
alter index index_name rebuild tablespace new_tablespace;

--moving the lobsegment(s) to the new tablespace
alter table table_name move lob (lob_column) store as
(tablespace new_tablespace);

--shrinking the table and lobsegment
alter table table_name enable row movement;
alter table table_name shrink space cascade;
alter table table_name modify lob (lob_column) (shrink space);

Table and the lob segment will shrink during migration, but just in case you need further space shrinkage i have included the scripts needed.

Datediff function in Oracle

As i am working on Oracle database at my day job, i have found something that is by default on sqlserver but not in oracle. That is the datediff function that given the input of two dates and an identifier like day, month or year returns integer with the requested number.

So to cut the long story short, i have written my own datediff function for oracle use. You can request more return types in the comments, and i will be glad to add them. Here is the code:

create or replace function datediff(v_type VARCHAR2, date_from DATE, date_to DATE) return integer as
v_diff INTEGER;
v_diff :=
  case upper(v_type)
    when 'MONTH' then
      months_between(date_to, date_from)
    when 'DAY' then
      date_to - date_from
    when 'YEAR' then
      trunc(months_between(date_to, date_from)/12)
    when 'HH' then
    (date_to - date_from) * 24
    when 'MM' then
    (date_to - date_from) * 24 * 60
    when 'SS' then
    (date_to - date_from) * 24 * 60 * 60
return abs(v_diff);

As you can see, the type parameters are: MONTH for difference in months, DAY for difference in days and YEAR for difference in years respectively.

I hope oracle will see the light and include this function in any of the future releases.

UPDATE: As my friend LILkillaBEE has mentioned that he could be in a need of hour/minute/second difference, i have added that too, so, this should be the final implementation.

New parameters are HH for hour, MM for minute and SS for seconds difference.

Sending an SMS message using .NET CF on Win Mobile

My best man asked me a few months ago to create him an app that would allow him to send a predefined sms to a predefined number on a click of a button using his Win Mobile phone. I thought about it and decided to write this application for him.

First thing that we need to do is to create a Smart Device project, and choose device application from the next page. In my solution i have one form called Sender and a Program.cs file, this is only the basics so we will not need anything more.

As you can see from the previous picture, the user interface is very intuitive and plain. We have two textboxes and a button that sends the SMS. This part of the application is completely working and can be used to send SMS from your Win Mobile phone.

For sending the SMS message we need only the code below, and of course the call from the Send button

using Microsoft.WindowsMobile.PocketOutlook;
public static void SendSms(string recipientNumber, string messageText)
var sms = new SmsMessage()
Body = messageText
sms.To.Add(new Recipient(recipientNumber));
MessageBox.Show("Message sent!");
catch (Exception ex)

To fire up the sending from a command line(that was the original idea if you remember, he wanted to be able to send it on a click of a button) we need to handle some command line arguments. My idea was to call the program the same way we have called the method that send the message first the recipient number, and then the message. calling the program without arguments would open the form, any other number of arguments will show a message with the correct way of doing it.

static void Main(string[] args)
switch (args.Length)
case 0:
Application.Run(new Sender());
case 2:
MessageBox.Show("Wrong number of arguments entered. Correct order is RecipientNumber \"SmsText in quotes\"");

We can also do a regular expression check depending on the numbers we allow the user to send the SMS to, if we want to limit the user in any way, because i know my only user, i believe i can trust him 🙂

Next thing you need is to set up a shortcut that calls the application using the parameters and bind the shortcut to a button on your device. Quick way to pay tram fare when the conductor enters the tram and you just forgot to buy the ticket that day.

Allow only one instance of MDI child in your VB.NET MDI application

I have encountered a problem in class today, we needed our Contact Manager application only to run one instance of every MDI child form, so the user will not be able to start unlimited(more than 1) number of Contacts form, or any of the settings forms. I have binged the solution and found a piece of code that allows something like that, but as i am teaching VB.NET here, i had to rewrite it from C# to VB.NET. The original C# Code provided by Roy Osherove is HERE
Here is the VB.NET code i have rewritten from Roy’s version:

Imports System
Imports System.Windows.Forms
Imports System.Collections.Specialized
Public Class MdiFormLoader
    Private m_InitializedForms As HybridDictionary = New HybridDictionary()
    Public Sub LoadFormType(ByVal formType As Type, ByVal mdiParentForm As Form)
        If (IsAlreadyLoaded(formType)) Then
        End If
        Dim frm As Form = Activator.CreateInstance(formType)
        frm.MdiParent = mdiParentForm
        AddHandler frm.Closed, New EventHandler(AddressOf FormClosed)
    End Sub
    Private Sub FlagAsLoaded(ByVal formType As Type)
        m_InitializedForms(formType.Name) = True
    End Sub
    Private Sub FlagAsNotLoaded(ByVal formType As Type)
        m_InitializedForms(formType.Name) = False
    End Sub
    Private Function IsAlreadyLoaded(ByVal formType As Type) As Boolean
        Return If(m_InitializedForms(formType.Name), m_InitializedForms(formType.Name) = True)
    End Function
    Private Sub FormClosed(ByVal sender As Object, ByVal e As EventArgs)
        Dim closingForm As Form = sender
        RemoveHandler closingForm.Closed, New EventHandler(AddressOf FormClosed)
    End Sub
End Class

You can call your form by using these 2 lines:

Dim _formLoader As New MdiFormLoader()
_formLoader.LoadFormType(GetType(ContactsMain), Me)

Creating ASP.NET MVC application against Oracle database pt. 1

This is a first in a series of posts, as i will try to build ASP.NET MVC application against Oracle XE database, but this example can be used for any Oracle database greater than 9i.

I will try to use Oracle the latest version that i can get from the Oracle Site.

With a little help from LILkillaBEE i created generic helpers that return IEnumerable<T> on which i can use LINQ and play with it.

First thing first, as i am creating a Contact manager application part by part, the first functionality i want to implement is getting the data from the Oracle XE database and working with it in MVC way. So i have created the table with personal data only in it.


  before insert on PEOPLE
  for  each row
    select PEOPLE_SEQ.nextval into  :NEW.PERSON_ID from  dual;


After this, i have created the Person class in my project

public class Person
    public virtual int PersonID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string AddressLine1 { get; set; }
    public virtual string AddressLine2 { get; set; }
    public virtual string ZipCode { get; set; }
    public virtual string City { get; set; }
    public virtual string Country { get; set; }

And an interface that i will implement later in my repository

interface IPersonInterface
    IEnumerable&lt;Person&gt; GetAll();
    Person GetById(int id);
    void Add(Person person);
    void Delete(int id);

EDIT: After considering to finish this tutorial i finally gave up because there is no easy way of doing this and i kept hitting the wall a few times.