Carmen-Rails Setup Tips

As its GitHub description reads, Carmen-rails is a Rails 3 plugin that supplies two new form helper methods: country_select and subregion_select. It uses carmen as its source of geographic data.  It is highly customizable and a demo is available if you’d like to give it a spin.

The Carmen-Rails demo uses an “Order” Model with the country and region selections. I’m using it on a User Model for geographic profiling as you see below. I am writing this post to share some tips from my experience of getting Carmen-Rails to do exactly what I wanted it to do.

Dual Use, i.e., Setting Defaults

The Carmen-Rails Gem readme covers everything you need to know to get up and running, complete with form partial, populating the region info in a subform partial using CoffeeScript and a supporting route.

Here’s the _fields.html.erb partial that the user registration and profile forms use.  We’ll want to display blank selections for a registration form and display the user’s Country and State on the Profile Update form.

The section at top is the profile update page of an existing user where the only real difference is that at #1 we’re specifying the @user.country_code in the region_options_for_select and adding a :sub_region when loading the subregion_select partial.

Subregion_Select Partial

The Subregion_Select partial is shown below. The first item to point out is at the left of #1.

<% if country.nil? %>

That wasn’t in the demo which I added to avoid a Rails Nil Object Reference Error.  Just below #1 is a dual use call to Carmen-Rails subregion_select_tag. If the user is signed-in, or on the profile update form in other words, we’re going to set the state_code to his account State.  We do that by using the :priority property.

Something I encountered with Carmen-Rails in my environment was that it wasn’t setting the selection control’s name and id values to the acceptable Rails/HTML names.  That’s why you see the :name and :id settings added as subregion_select_tags html_options.

CoffeeScript Url Tip

The demo used an “/orders/subregion_options?parent…” url. My subregion selection was not displaying so I entered the “/users/subregion_options?parent…” url in the browser and discovered I was getting a routing error because “there was no user with id subregion_options.” Passing the user’s ID in the url (/users/ID/subregion…) worked, but it played no role in the logic of populating the subregion so I modified the url and its corresponding route to “/subregion_options?parent…” as you see below.

The Verdict

Carmen-Rails is a very useful Gem that I plan on using for a long while. Hopefully these setup tips will make your experience with it even better than mine.