Rails 3, jQuery and multi-select dependencies

I’ve just upgraded to Rails 3 and hit a real blocker that’s taken me two days to work out. I hope this post can save someone else even a few hours of stuffing around with Rails 3, jQuery, unobtrusive javascript and other assorted gems.

The problem

I have a user profile form with dropdown selects for country, region and city. To start out, only the country select is populated. When the user selects a country, the region select populates with regions from that country, when a region (aka state/territory) is selected, the city list is populated. I know there are countries that don’t have regions, but that’s another day’s thinking.

My setup is fairly simple. I’m using jQuery, NOT prototype, so there’s no observe_field. Try to use such will result in an error ‘observer_field undefined method’. I’m using formtastic as a UI helper because I’ve been impressed by it’s DRYness and I’m tired of coding html forms. This solution shows the formtastic layouts, but can be applied to standard rails forms very easilyy.

jQuery setup

I’m using the jQuery 1.4.2 minimized version of the file from Google and a jquery/ujs wrapper/helper file I downloaded from github at http://github.com/rails/jquery-ujs/blob/master/src/rails.js.
I renamed this file as rails.jquery.js and copied it to the folder public/javascripts/ under the root of my application folder.

Next step is to update the javascript files that are included in the header of your application. So, open up app/views/layouts/application.html.erb

 <%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "rails.jquery.js", "application.js" %>
  <%= csrf_meta_tag %>

The javascript_include tag lists specifically those files I need. If you use the “defaults” option you’ll end up with the prototype.js included in the mix. This is something I’m trying to avoid given it’s not UJS.

The csrf_meta_tag reference is a Rails 3 enhancement. It seeks to avoid cross site scripting issues by ensuring the token created by the authenticated visitor is maintained throughout the site, thereby ensuring that a button click or post back has actually come from a genuine session.

Update routes.rb

When a change of a select list is triggerd, an Ajax post will be made to my profiles controller (remember we’re dealing with the ‘profile’ model here). I’m using two actions, update_state_select and update_city_select.
To add these calls into the routes.rb file, update it with the following:

resources :profiles

  match 'profiles/update_state_select/:id', :controller=>'profiles', :action => 'update_state_select'

  match 'profiles/update_city_select/:id', :controller=>'profiles', :action => 'update_city_select'

The main form

The form where users can enter their new profile details is called new.html.erb and resides under the app/views/profiles folder. It’s a formtastic form, but once you’ve seen the code, you can do the mental shift to whatever other UI component you fancy.

<% semantic_form_for @profile, :remote=>true, do |form| %>
    <% form.inputs do %>
        <%= form.input :firstname %>
        <%= form.input :middlename %>
        <%= form.input :lastname %>
        <%= form.input :image, :as=> :file %>
        <%= form.input :timezone_adjustment, :as=> :time_zone %>
        <%= form.input :gender, :as => :radio, :label => "Gender", :collection => [["Male", "M"], ["Female", "F"]] %>
        <%= form.input :birthday, :as=> :date, :start_year =>1930 %>
        <%= form.input :facebook_profile_url %>
        <%= form.input :linkedin_profile_url %>
        <%= form.input :country_id, :collection=>Country.find(:all, :order=>:name).collect{ |c| [c.name,c.id]}, :required=>true %>
        <div id="addressStates">
        <%= render :partial => 'states'  %>
        </div>
        <div id="addressCities">
      <%= render :partial => 'cities'  %>
    </div>
    <%= form.buttons :commit %>
  <% end %>
<% end %>

Handle the change events

We have to add in the javascript now that will get fired when the first select (the country list) is changed. This is a piece of javascript code I’ve decided to put into the application.js file under the public/javascripts file.
The code looks like this:

jQuery(function($) {
  // when the #country field changes
  $("#profile_country_id").change(function() {
    // make a POST call and replace the content
    var country = $('select#profile_country_id :selected').val();
    if(country == "") country="0";
    jQuery.get('/profiles/update_state_select/' + country, function(data){
        $("#addressStates").html(data);
    })
    return false;
  });

})

What’s happening here is the jQuery code is waiting for a change to be triggered by a control called ‘profile_country_id’. When a change is detected, it’s taking the value of the selected value and passing it as a parameter to the get call on profiles/update_state_select. The results of the call will end up being rendered as html in the addressStates div.

If you have firebug installed (and you should!!) you can see the javascript get being triggered in the console window. If you haven’t implemented the update_state_select method in your controller, you’ll probably get a 404 error.

The controller

This is the simple bit apart from a few minor tweaks to accommodate Rails 3 ActiveRecord queries

def update_state_select
    states = Region.where(:country_id=>params[:id]).order(:name) unless params[:id].blank?
    render :partial => "states", :locals => { :states => states }
end

Note the use of the ‘where’ and the ‘order’ methods applied directly to the entity name. I think this is one of the neatest changes in the Rails 3 ActiveRecord domain. I’m going to have to build an automation utility to update all my old code.

Rendering the partial

In the simplest case, the partial that displays the states should just be a select populated with the results of the update_state_select method call. There’s a ‘but…’ coming up so pay attention.

#This is _states.html.erb stage 1 - without the jQuery code
<%= semantic_form_for "profile", :remote=>true, do |form| %>
  <%= form.inputs do %>
    <% if !states.blank? %>
      <%= form.input :region_id, :collection=>states.collect{ |s| [s.name,s.id]} %>
    <% else %>
      <%= form.input :region_id, :collection=>[] %>
    <% end %>
  <% end %>
<% end %>

So far it’s looking good, when a user selects the country drop-down the jQuery event is triggered, that does a Get to the controller. The controller builds a collection and passes it to the _states partial. However, (this is the ‘but’ I mentioned) I couldn’t get the change event of the state drop-down unless I put the jQuery code in as part of the partial. If anyone knows what/how to add this code to the application.js and still get it to fire, please let me know.

To get the change event of the state_id select to trigger, add the following code to the top of the _state.html.erb file. Note how similar it is to the code in the application.js file

<script type="text/javascript">
jQuery(function($) {
// when the #region_id field changes
  $("#profile_region_id").change(function() {
    // make a POST call and replace the content
    var state = $('select#profile_region_id :selected').val();
    if(state == "") state="0";
    jQuery.get('/profiles/update_city_select/' + state, function(data){
        $("#addressCities").html(data);
    })
    return false;
  });
})
</script>

Now we have a functioning form with an Ajax enabled country and state select lists. All that’s left to do is to do a copy and paste of code in the profiles controller to get the update_city_select method working and add a new _cities.html.erb partial to display the results of the controller method call.

Here’s all the relevant code for the controllers/profiles_controller.rb file:

def update_city_select
    cities = City.where(:region_id=>params[:id]).order(:name) unless params[:id].blank?
    render :partial => "cities", :locals => { :cities => cities }
end

And the code for the app/views/profiles/_cities.html.erb partial:

<%= semantic_form_for "profile", do |form| %>
  <%= form.inputs do %>
    <% if !cities.blank? %>
      <%= form.input :city_id, :collection=>cities.collect{ |c| [c.name,c.id]} %>
    <% else %>
      <%= form.input :city_id, :collection=>[] %>
    <% end %>
  <% end %>
<% end %>

Summary

I hit the first wall when I added an observe_field and couldn’t explain why I was getting method undefined errors. That started me down a long and winding road of frustration. I think I’ve overcome most of the frustrations and I’m starting to get the hang of the Rails 3 changes.

There is a plugin that will allow you to keep your old Rails 2 ways alive but every time I saw mention of it, I also saw comments about how bad an idea it is. I mean, you could probably also run some COBOL code as a plugin, but why live in the past?

References

jQuery files from Github

Formtastic plugin

Beware: Use the proper branch for Rails 3 gem ‘formtastic’, :git => “http://github.com/justinfrench/formtastic.git”, :branch => “rails3″

Simone Carletti’s Blog

Ryan Bates’ excellent video cast series

Comments, questions and suggestions welcome

  • Share/Bookmark

Ruby/Rails 3 and PostgreSQL

I’ve just spent an hour arguing with a new install of ruby 1.92, rails 3.0.2rc and PostgreSQL.

Every time i tried to do a db:migrate I got a strange error.

rake db:migrate
(in /home/peter/projects/workspace/testapp)
rake aborted!
no such file to load -- pg

I did the usual trawling around helpful websites, each suggesting I hadn’t the correct database gem installed. some referred to pg, some to postgresql, other to ruby-postgres.

What I have installed is listed below

abstract (1.0.0)
actionmailer (3.0.0.rc)
actionpack (3.0.0.rc)
activemodel (3.0.0.rc)
activerecord (3.0.0.rc)
activeresource (3.0.0.rc)
activesupport (3.0.0.rc)
arel (0.4.0)
builder (2.1.2)
bundler (1.0.0.rc.2)
capistrano (2.5.19)
erubis (2.6.6)
highline (1.6.1)
i18n (0.4.1)
mail (2.2.5)
mime-types (1.16)
minitest (1.6.0)
net-scp (1.0.2)
net-sftp (2.0.4)
net-ssh (2.0.23)
net-ssh-gateway (1.0.1)
pg (0.9.0)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.9)
rack-test (0.5.4)
rails (3.0.0.rc)
railties (3.0.0.rc)
rake (0.8.7)
rdoc (2.5.8)
sqlite3-ruby (1.3.1)
thor (0.14.0)
treetop (1.4.8)
tzinfo (0.3.22)

The fix for the 'no such file to load — pg' error is to update the new Gemfile file in your application’s root folder.

#Comment out the sqlite3 requirement
#gem 'sqlite3-ruby', :require => 'sqlite3'
#Add a pg requirement
gem 'pg', :require => 'pg'

Once you’ve done this do a bundle install from your application root folder. This ensures you have all required gems installed. Another hour wasted fighting against the machine.

$ sudo bundle install
  • Share/Bookmark

Internationalized country/state/city database

I’ve just posted a little project up to the gitorious website for my and other’s pleasure. The last few freelance projects I’ve worked on have required the functionality to provide users with a way to enter their location using a prompt system by selecting country first, then entering their region/state and finally their town and city. The database structure uses a standard Rails convention and is MySQL based. It can be very easily converted to any other SQL supported format.

Click here to browse to the project.

  • Share/Bookmark

Ubuntu 10.04 setup for Ruby on Rails and general use

This extract is from notes I took during the process of setting up both a desktop and laptop for general use as a development environment for Ruby on Rails (RoR) and PHP development.

There were lots of other steps (custom gems and environment stuff I like), but most of what follows is generic enough to get the basics in place. Happy Hacking!!

Installing Skype

sudo apt-get install libqt4-dbus libqt4-network libqt4-xml libasound2
sudo dpkg -i skype-ubuntu-intrepid_2.1.0.81-1_amd64.deb

Installing Amarok

sudo apt-get install xine-ui libxine1-ffmpeg

To get remote shares mapping in fstab.

Firstly, install the smb client package

sudo aptitude install smbfs
sudo apt-get install portmap nfs-common

Then add the following line to /etc/hosts.deny:

echo portmap : ALL>>/etc/hosts.deny

By blocking all clients first, only clients in /etc/hosts.allow below will be allowed to access the server.

Now add the following line to /etc/hosts.allow. User your own IP address.

echo portmap : 192.168.0.20>>hosts.allow

Next create the mounting points on your system

sudo mkdir /mnt/<name of mounting point>
sudo mkdir /mnt/music
sudo mkdir /mnt/backups

Create a file in home folder called .smbcredentials (note the leading dot)

touch ~/.smbcredentials
echo username=[your network username] >> ~/.smbcredentials
echo password=[your network password] >> ~/.smbcredentials
chmod 600 ~/.smbcredentials

Now an entry in /etc/fstab using the ip address of your NAS

#Added a permanent share to shares on NAS box
#Note: everything that follows (up to the 0  0 should appear on the one line)
#and one line is required for each share you want to map

//192.168.0.20/<foldername on NAS> /mnt/<local foldername> cifs
uid=peter,credentials=/home/peter/.smbcredentials,domain=office,dir_mode=0777,file_mode=0777 0       0

Now, for a few of the other standard tools
Setup filezilla and limewire

sudo aptitude install filezilla

#Limewire - download LimeWireLinux.deb from limewire site
# reports missing dependencies
sudo dpkg -i LimeWireLinux.deb
limewire-basic depends on sun-java6-jre | icedtea-java7-jre |
sun-java6-jdk | icedtea-java7-jdk; however:
Package sun-java6-jre is not installed.
Package icedtea-java7-jre is not installed.
Package sun-java6-jdk is not installed.
Package icedtea-java7-jdk is not installed.
dpkg: error processing limewire-basic (--install):
dependency problems - leaving unconfigured

Open synaptic package manager. Go to the Settings/Repositories/Other sources tab.
Check the two default partner sites. Reload the package list and select the following

sun-java6-jre
sun-java6-plugin
sun-java6-fonts packages

Now retry limewire and you’re smoking.

Installing ruby and associated gems

sudo apt-get install ruby
sudo apt-get install rubygems
sudo gem install rake
sudo gem install rails

I tried to install capistrano using sudo but it wasn’t working on laptop however it did work on desktop

gem install capistrano

Then change ~/.bashrc to include path to new gems

emacs ~/.bashrc &
export PATH=$PATH:~/.gem/ruby/1.8/bin:/var/lib/gems/1.8/bin

Now install and configure mysql before trying to install any of the ruby mysql gems

install mysql server
sudo apt-get install mysql-server

Setup prompts you for a password – enter it, remember it and enter it again.

Install the mysql admin tools

sudo apt-get install mysql-admin

NB – must install the libmysqlclient[nn]-dev package
This has mysql_config bundled with it which is needed by the ruby gems

Execute the following to find out what version of libmysqlclient you’re running

dpkg --get-selections | grep mysqlclient

In my case it’s version 16, so execute the following

sudo apt-get install libmysqlclient16-dev

Next, you NEED TO INSTALL the ruby1.8 dev package
If you don’t you’ll get all sorts of mysql gem errors — frustrating!!!

sudo apt-get install ruby1.8-dev
sudo gem install mysql

Installing and configuring git

sudo apt-get install git-core
git config --global user.email

Installing apache

sudo apt-get install apache2

The line above should do it, if you get any glitches, try the following

sudo apt-get install apache2.2-bin
sudo apt-get install apache2.2-common
sudo apt-get install apache2-threaded-dev

Installing php

sudo apt-get install php5
sudo apt-get install php5-mysql

Anything else is stuffing around with particular ruby gems and dev tools so probably too specific for this note.

  • Share/Bookmark