Super Spread Sheet S³

Or little computing tricks and hacks

Category Archives: Ruby on Rails

Rails: When join tables have no class

I was revisiting an old project of mine, where I had brilliantly created a join table. I had forgotten, though that I did not create a Rails model, because I did not need one. So coming back to the project, I wanted to count the number of rows in that join table in the command line, rails c.

Surprise! I cannot find the the class name, so I cannot access the table directly there…

Instead, I ran psql database_name:

# \dt;
# SELECT * FROM database_name;

to get the list of all the rows in the table.

The join table I created, joins the ids of other two tables: article and category. In was of the models one find the following statement: has_and_belongs_to_many.

To access the information in the table in the rails console, where c is an object of catergory:


which returns an array of the article ids which are associated with that category. The other direction also works. Given a an object of article:


returns an array of categories to which the article belongs to.

When in doubt, read the docs:


git: comparing with remote branches

I have a Rails app which is deployed in Heroku and its source is in bitbucket. In Heroku I have in fact two instances: staging and production. When I came back after a break on the project, I wanted to compare what was deployed or committed where, as I knew that a JavaScript bug had prevented me to have a full deployment.

git works with branches so the comparison I want to make, takes place between branches, regardless of where they are located.

To lists local and remote branches, run the command:

git branch -a

The output for my app looks something like this:


The first line is the local working branch, the second in the remote master branch in bitbucket, the last two lines are the production and staging branches in heroku.

I can simply run git diff with the name of the two branches to get a detail description, line by line, of the differences:

git diff remotes/heroku/master remotes/staging/master

To get the list of only the files that are different, use the following command:

git diff --stat --color master remotes/heroku/master


Dear App, why are you giving me the wrong date?

Localization has always amazed me. But I also giggle when developers get it wrong. I know for experience that it is not obvious. How does the app know what language do you speak if you leave in Montreal, Switzerland or Belgium, where there are more than one official language? And that is when when the user wants to use the app in one of the official languages.

Added to that are the timezones and daylight savings shifts in one place throughout the year. I am originally from Colombia, where even the notion of seasons is summarized as the rain and dry seasons. Don’t ask me when each is supposed to be! Change of time in Summer? Forget it. “Wow, are you really going to sleep now, aunty, here we are going to have lunch!” The internet brings these issues to the fore and forces the need for solutions. The infrastructure is there to be used.

The last time I stumbled upon timezones was when implementing the events section of my Rails app. The first surprise was to find that the time I saved was shifted. The reason made perfect sense. The canonical storage timezone in the database is UTC and the display can be done in a timezone of your choice. Cool. I adjusted the configuration and added to the config/application.rb file the following line:

    config.time_zone = 'Eastern Time (US & Canada)'

That worked just fine in my local development platform: the storage was done in UTC and the display in EST/EDT depending on the time of the year, with the following code:

    event.my_date.to_formatted_s(:long_ordinal) %>

But when I deployed to heroku, the initial problem came back. I realized that it had something to do with the local timezone of the machine, somehow. As would only make sense, the heroku server is running in UTC time. However, even if the default timezone read EST, the actual saving into the database was done simply by striping the timezone: 17h00 EST became 17h00 UTC.

I could not find a reason, but that does not matter. The point is to make the app work standalone, independently of where it is deployed.

I tried several paths:

1. I added an extra line to the config/application.rb as follows:

    config.active_record.default_timezone = 'Eastern Time (US & Canada)'

However, that line just made the previously saved my_date fields disappear.

2. I then used the use_zone command to create a block, where the default timezone would be defined:

Time.use_zone("Eastern Time (US \& Canada)") {
        time_entered =
        @event.the_date = time_entered

This was a step forward, the time_entered was produced in the correct timezone but the assignment and then saving in the database, simply stripped off the timezone information.

3. After much trial and error, the solution was to create an object with the UTC offset. This offset had to be dependent on the entered date, as daylight savings for that date is what matters.

The final solution is:

      Time.use_zone("Eastern Time (US \& Canada)") {
        time_entered =
        the_offset =
        new_time =
        @event.my_date = new_time

The code for viewing the date, did not change.

If you have any further comments or explanations, please send them this way.


Google maps in a Rails app

My Rails app has Events which have location which of course needs to be shown in a map. With the postal address of a location, its latitude and longitude can be calculated through a geocoding conversion. With them, the location can be plotted in a map.

The Google Geocoding API does just that.

For example, by entering the following URL: in a browser, a JSON string is retrieved which includes the latitude and longitude of an office building located at “800 Boulevard Rene-Levesque, Ouest” in Montreal, Canada, where one of the events took place:

   "results" : [
         "geometry" : {
            "location" : {
               "lat" : 45.5009512,
               "lng" : -73.5675947

However, this is one of the last steps. Let’s start with the Rails side.

Include a map in a Rails app

Before being able to use the geographical coordinates just retrieved, we need to tell Rails to include the map. This requires some JavaScript. First, I want to include a fixed map.

I added to the app/views/events/show.html.erb the following:

The first script brings in the necessary tools to draw the map. It can be included in the app/views/layouts/application.html.erb as follows:


The second script delays the map related scripts until the page if fully loaded. Here is a good explanation.

The third section defines how the map will be displayed. The CSS portion defining these two elements is:

#map-container {
   height: 400px;
   border-radius: 16px 16px;
   border-color: #fff;
   border-style: solid;
   box-shadow: 2px 2px 10px #B1B1B1;
   margin-top: 25px;
   border-width: 7px;

#map-canvas {
   height: 384px;
   width: 100%;

The script to initialize the map is as follows:

# app/assets/javascripts/gmap.js

function initialize() {
    ## Initialize the map parameters
    var center = new google.maps.LatLng(45.5009512, -73.5675947)
    var mapOptions = {
        center: center,
        zoom: 16
    ## Initialize the map object and attach it to the element with id 'map-canvas'
    var map = new google.maps.Map(document.getElementById('map-canvas'),

    ## Initialize the marker and attach it to the previously created map
    var marker = new google.maps.Marker({
        position: center,
        map: map,
        title: "Here! Ici!"

These scripts and code snippets produce the following map with a marker centred in downtown Montreal:


The map according to the event address

Having this in place, next is to feed the geographical coordinates corresponding to the event’s address to the initialize function to display the map. However, when I changed the function to

  function initialize(lat,lon)


  google.maps.event.addDomListener(window, 'load', initialize(lat,lon));

I had the following error:

 Uncaught TypeError: Cannot read property 'offsetWidth' of null

After looking high and low and bearing with my inexperience with JavaScript, I found the answer here: simply move the div defining the map-canvas and map-contianer in the show.html.erb file, above the script calling the initialize function.

Latitude and longitude from a postal address

I decided to calculate the latitude and longitude only when the postal address (map_address) is created or updated. In the controller this corresponds to the update and create methods. I wrote a function and included it in app/controllers/events_controller.rb as follows:

  def lat_lon(address)
    # Replace spaces by + signs, escape any other characters and
    # convert the string into a url object.
    url = URI.parse(
        '' +' ', '+')
    # Make the request to retrieve the JSON string
    response = open(url).read

    # Convert the JSON string into a Hash object
    result = JSON.parse(response)
    lat = result['results'][0]['geometry']['location']['lat']
    lon = result['results'][0]['geometry']['location']['lng']
    return lat, lon

The preliminary test suite worked fine, but I missed one test. As you may know, Montreal is a bilingual city and addresses are also found in French with non-ASCII characters. Browsers tend to be more lenient and flexible, and accept characters which otherwise would throw an exception in a strict conversion into a URI element. So,é-Levesque+O+Montréal will work just fine, having the address equal to “800 Boulevard René Levesque, Montréal” as an input to the lat_lon method above, will throw an error:

URI::InvalidURIError: bad URI(is not URI?)

The solution was to use the URI method escape to transform all the unsafe characters including the space.

Final version of code

For the sake of completeness, here are the revised scripts:

# app/controllers/events_controller.rb
require 'net/http'
class EventsController < ApplicationController
  def create
    ..., @event.lon = lat_lon(@event.map_address)


  def update
    ..., @event.lon = lat_lon(params[:event]['map_address'])


  def lat_lon(address)
    # Escape any non_ASCII characters and convert the string into a URI object.
    encoded_url = URI.escape(
      '' + address
    url = URI.parse((encoded_url))

    # Make the request to retrieve the JSON string
    response = open(url).read

    # Convert the JSON string into a Hash object
    result = JSON.parse(response)

    # Extract the latitude and longitude and return them
    lat = result['results'][0]['geometry']['location']['lat']
    lon = result['results'][0]['geometry']['location']['lng']
    return lat, lon
# app/assets/javascripts/gmap.js

function initialize(lat,lon) {
      var center = new google.maps.LatLng(lat, lon)
      var mapOptions = {
        center: center,
        zoom: 16
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var marker = new google.maps.Marker({
      position: center,
      map: map,
      title: "Here! Ici!"



Leave any questions or comments at the bottom! I would love hearing from you!

Helpful links

Rails: Different storage for carrierwave assets depending on the environment

I am using carrierwave for storing images, one (or more) per field of a table in a database of the my Rails app. Given that heroku does not allow assets to be uploaded by the user, or dynamically for that matter, I had to use storage in the cloud. Mind you, not a bad thing. I chose AWS, s3 services to store my bucket.

Carrierwave has an extensive explanation on setting up the right configuration variables to allow the storage on the cloud. (Carrierwave in github)

The first problem I had was running the development and staging (or production) sites at the same time: Updates in one were seen in the other in the following case:

  1. Create a field with id=1 in production. The image associated with it, is stored in the cloud with id=1.
  2. Create a field with id=1 in development. the image associated with it, overrides in the cloud, the previously created image.

My solution to solve this problem was to create a second bucket, and add in the file


the setting as follows:

# config/initialize/carrierwave.rb
  if Rails.env.production?
    config.fog_directory = 'bucket-0'
  elsif Rails.env.development?
    config.fog_directory = 'bucket-1'

The next problem was that the test suite run was affecting the development data in the same way as described before. In fact, I wanted the images for the test suites simply to be stored locally and then deleted. The first approach was to include in the same file as above the following:

# config/initialize/carrierwave.rb
  if Rails.env.test? || Rails.env.cucumber? = :file
    config.enable_processing = false
    config.root = "#{Rails.root}/tmp"
  else = :fog

  config.cache_dir = "#{Rails.root}/tmp/uploads"

And to delete after finishing the test, add to the file:


the following:

# spec/spec_helper.rb
RSpec.configure do |config|
  config.after(:all) do
    if Rails.env.test?

That only seemed to work. I think that the display was using cache data. Only recently did I notice the problem when reworking some aspects of the app. The images in development were being overwritten by the test suite.

I had to add the following to the uploader file

# app/uploaders/image_uploader.rb
  if Rails.env.test?
    storage :file
    storage :fog

Et voilá!

When system upgrades break gem dependencies

After recently upgrading to Ubuntu 15.04 (almost ready for the next release!), my gem dependencies were broken.

... /lib/mysql2.rb:31:in `require': 
Incorrect MySQL client library version! 
This gem was compiled for 5.5.43 but the client library is 5.6.24. (RuntimeError)

Neither bundle nor bundle update changed the gem. Only uninstalling the gem forced the correct update:

gem uninstall mysql2
bundle install

Solution taken from

Restarting unicorn after boot using mina and nginx in Rails

My teammate did a wonderful job at setting up a droplet in Digital Ocean to host a Rails app. Most of the details are here.

All of the reference to directories are based on having exactly the set up described in that blog post.

However, we noticed that unicorn was not being restarted after booting, having to do so by hand. Not quite a problem if you are on developing/staging states, but in full production a real problem. Except, we could not use a simple command line, because unicorn has to be started by mina.

Looking at the config/deploy.rb file, I noticed the following:

    to :launch do
      invoke :'unicorn:restart'

so the command line to start unicorn should be:

mina unicorn:restart

Actually the command only works if in the correct directory: /home/deployer/my-app-name/current as follows:

bundle exec mina unicorn:restart

So now, all I had to do was to turn that command into a script called at boot. By the way, the droplet uses Ubuntu.

After a few attempts, I created a file called /etc/init.d/my_unicorn, you have to have root privileges for this, with the following format:

#!/bin/sh -e
# upstart-job

echo "starting unicorn after reboot"
exec sudo -u deployer sh -c "cd /home/deployer/my-app-name/current && /home/deployer/.rbenv/shims/bundle exec mina unicorn:restart"

(Looking back “-u deployer” might not be needed but I did not test it.)

By just adding that script, I was able to run

$sudo service my_unicorn start

But, it was not being called at boot yet. I needed to add new service (i.e. my_unicorn) to startup. For that, the following command is needed:

sudo update-rc.d my_unicorn defaults

And that should have worked on reboot, but it wasn’t.

Every time mina is called, it asks for authentication, and after 3 failed attempts it quits with an error. The solution was to create a ssh key and add it to the authorized_keys file, the same way you do for sites like github.

And that is it, if I haven’t forgotten anything!

Ckeditor in heroku

I was reaaaally happy to have found the ckeditor gem. As my grandmothers used to say: “Mató dos pájaros de un tiro” (killed two birds with one shot). The gem took charge of all the type setting of the articles INCLUDING adding pictures to the body of the text.


Everything worked like magic in my test environment, until I deployed to heroku. All charms gone, it did not work. Where the editing window was to go, it was just nothingness.

The solution taken from here:

Make sure to

bundle update ckeditor

and then, add these line to config/application.rb

config.assets.precompile += Ckeditor.assets
config.assets.precompile += %w( ckeditor/* )
config.autoload_paths += %W(#{config.root}/app/models/ckeditor)

and that worked for me.

Sorting out time zones in Rails

NOTE: Post edited 9 March, 2015.
Original post had incomplete information. The solution given was not enough.

Nothing more annoying that an app which cannot sort out or at least tell you in what time zone the date displayed is given in.

Standard for Rails apps are the fields created_at and updated_at. By default Rails uses UTC to store this, but when this command is issued

the time is adjusted to show local time. This creates an odd situation when you use to set in the database a time field through an input form. The time is stored without transformation in UTC.

Furthermore, ruby only supports UTC. By typing


I discovered that these are in fact of Class


which is (taken from ActiveSupport TimeWithZone) a

Time-like class that can represent a time in any time zone.

To sort out any discrepancies or errors with respect to you application, the time zone should be set. To find the available zones type

rake -D time

for the commands available and

rake time:zones:all

to get a listing of all the time zones recognized. Or try

rake time:zones:local

There seems to be different places to set the time zone:

  • config/environment.rb was mentioned in this post.
  • config/application.rb is where the commented portion with the explanations, was.

I used the latter, with the following line:

    config.time_zone = 'Eastern Time (US & Canada)'

This magic line

… sets default to the specified zone and makes Active Record auto-convert to this zone.

is misleading, since I discovered that in the database dates are indeed and still stored in UTC, after all the changes.

To fix this, once the current date is captured, it is converted into UTC before storing in the database.

A snippet of the new.html.rb:

      my_date_time =

        datetime_separator: " at ",
        prompt: {day: 'Day', month: 'Month', year: 'Year',
                 hour: 'Hour', minute: 'Minutes'})

and in the controller.rb:

def create
    time_in_localzone =
    @article.published_on = time_in_localzone.utc

      redirect_to articles_path
      render 'new'

Useful links:

Rails: Choosing and assigning in a HABTM association

Now that I have an HABTM association, I need to provide the user with an interface to choose different categories for an article. (To see how I created the association, see this post.)

Because we have in each of the model files the line stating the association:

# app/models/category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :articles


# app/models/article.rb
class Article < ActiveRecord::Base
  has_and_belongs_to_many :categories

this generates the method:


which returns an array of the category ids which the article object belongs to. Reciprocally the method


returns an array of the article ids in that category object.

To choose a category, in the new.html.erb and edit.html.erb files I included the following (I apologize for the lack of the closing %>, but when I include them, the pre environment just disappears the line):

<% Category.all.each do |cat|
  <% check_box_tag "category_ids[]",, @article.categories.include?(cat)
<% end 

the first argument to check_box_tag is the name of the check box and the [] are very important to indicate that it is an array being passed. The second argument is the value, and the third is a boolean indicating whether the box should be ticked or not.

When the article is updated, the method category_ids updates the categories of the article using the array that was passed in the params hash. The category_ids method was generated by the has_and_belongs_to_many in the Article model.

In the controller, I included the following line as well

    @article.category_ids = params[:category_ids] ||= [8]

where 8 is a default value if nothing is given. If this line was not included no changes are made. This is in disagreement with the code in Bates’ Railscast, which is where I took the inspiration from. (I seem to recall a change in the params hash structure but I am uncertain.) I opted for the change by looking Rails API dock.