Rails Radio Button Mystery

Once I have to handle radio buttons in rails, I always need to look up the syntax again – especially of the attributes. So I wanted to print the most important issues down:

At first, we need to know how the normal html radio button behaves. A radio button is an input field with type radio with the following attributes:

  • name: Individual name of the radio button. If many have the same name, they belong to the same group.
  • value: value that is send when submitting the form
  • checked: if the value is checked when loading the page or not

Now looking at the rails function we have the following attributes to the radio_button function:

  • object_name: name of the object that should be set
  • method: name of the method that should be set
  • tag_value: value that should be set
  • options: can set checked: true

Irritating is, that if you use f.radio_button on a form, the object_name parameter is automatically assigned and you only have to specify the other parameters.

Example in bootstrap together with a label:

<div class="form-group">
  <div class="col-sm-8 col-sm-offset-2">
    <div class="radio-inline">
      <% CalendarColor.find_each do |calendar_color| %>
          <%= f.label calendar_color.id do %>
              <%= f.radio_button :color_id, calendar_color.id, checked: calendar_color.default_color %> <%= color.name %>
          <% end %>
      <% end %>

Handle simple remote modal dialogs in rails applications

I will show you how to handle simple remote modal dialog rendering in rails apps.

Sometimes we do not want to write big javascript applications to have working remote modals in our rails applications. And rendering modals on the client is to bit of a hassle? Why not let the server (fastest html renderer in town) respond with complete dialogs?

Iam using Bootstrap Modals for this example. But it will work for any JS modal library.

Step 1 – Add a new modal layout.

<!-- app/views/layouts/modal.html.erb -->
<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <%= yield %>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

We also need to define a place where the dialogs will be rendered. Add the following to the application layout file.

<!-- app/views/layouts/application.html.erb -->
<div id="modal-holder"></div>

Step 2 – Add modal javascript

This will enable links with data-behavior=”modal” attribute to be rendered in modal windows.

$ ->
  modal_holder_selector = "#modal-holder"

  $(document).on "click", "[data-behavior='modal']", ->
    location = $(this).attr("href")
    $.get location, (data)->

  $(document).on "ajax:success", "[data-behavior='modal-form']", (event, data, status, xhr) ->
    # make sure this event is observered by document and not by dom node itself.
    url = xhr.getResponseHeader("Location")
    # Navigates to given location header in http response or closes the modal handler.
    if url
      window.location = url
      # FUTURE TODO: make sure only the modal which was called last will be destroyed.

Step 3 – Modify controller action

Now change the render layout for the controller action like so:

class ApplesController < ApplicationController
  def new
    @apples = Apple
    render layout: 'modal'

Step 4 – Use it

<%= link_to 'Create apple', new_apple_path, data: { behavior: 'modal' } %>

Please make sure the rendered form will have a data-behavior=”modal-form” attribute to successfully close the dialog after valid ajax response.

Rails Model Translations

As described in the Rails Guides for translating Active Record Models, you can use the methods Model.model_name.human and Model.human_attribute_name(attribute) to transparently look up translations for your model and attribute names.

This becomes very handy when you use form_for in Rails. You do not even have to write Model.human_attribute_name(attribute) because its content will be loaded automatically. Example:

Your active record model i18n file might look like this:

        one: Webinar presenter
        other: Webinar presenters
        webinar_id: Webinar
        presenter_email: Presenter email

Then this will automatically load the depending attribute names for the set locale:

<%= form_for @webinar_presenter do |f| %>
  <%= f.label :presenter_email %>
  <%= f.text_field :presenter_email %>
<% end %>

Because we had to translate some projects I wrote the I18n Model Translator Gem a little gem that has some rake tasks available to generate those i18n model files automatically for the english language, given that you have used descriptive column names for you models. Feedback is very welcome.

Rails: Time, DateTime, Timezones…. wait, what?

Everything happens in UTC!
Thats the one basic thing you must know about handling Times in Rails.

SomeModel.create(:time_attribute => Time.now)
SomeModel.create(:time_attribute => Time.zone.now)

Both lines will insert the same value into the database –> UTC+0. ActiveRecord will automaticly convert the given time. Therefore the config.time_zone in application.rb only controlls the default timezone and not the Timezone format the database will store the attribute.

You can also safely compare times that are in different zones – you don’t need to convert them to some common timezone.

A good link I found while adding time zones to our own project was this: http://www.redguava.com.au/2010/12/rails-basics-handling-user-timezones-in-rails/

I18n Rails – How to organize your locales in larger projects

As our rails projects grow bigger and bigger, the i18n locale files easily get messy and will loose their structure after a while. Especially when you have multiple software developers work on the same project.

So we develped a solution for us that is easier to handle and to maintain. The starting point is from the ruby on rails guides combined with this blog post:

We separated our yml files to the folders given by the rails structure. The yml files themself are also structured that way. This is a bit more efford in the beginning, but it is very nice to maintain, because you always know, where you have to put your locales and always know where to look for them!


Each file now only handles the content of one logical controller unit. The views/surveys files now have the content for each action. We group them in the action to logical groups that always look the same. We have a title, the breadcrumbs and then we have a unit for each form.

          text: :defaults.surveys
            text: :defaults.surveys
              placeholder: 'Search surveys...'
                text: 'Search'
                label: 'Topics'
                  placeholder: ''
                label: 'Title'
                  placeholder: ''
          text: :views.defaults.search
          disable_with: :views.defaults.form.searching

The problem with a solution like that is, that you have lots of redundant data. Take breadcrumbs for example. In each views folder there are different actions that have the same breadcrumb navigation. But there is a nice feature that you can use for that:

We put all business dependend locals into the defaults or views/defaults folders and reference them with e.g. :defaults.surveys. That makes it easy to have on each page every element, that can be translated to each language, but also removes redundant translations. But if you come to a language that make it harder to translate everything with the same translation you can translate that one separately!! Which can be quite important for example for languages like chinese.

Why Ruby on Rails

Why Ruby on Rails

I am writing software about 10 years by now. The last 3 years I was delighted by the great web application framework Ruby on Rails, which I don’t want to miss anymore. I want to publish articles in this blog every now and then and will mostly write about this awesome framework. So I want to tell you some good reasons, why I like to use it:

  1. Rails is good for rapid prototyping
  2. Ruby is easy to learn
  3. Rails code is easy to read because of the given structure

Rapid prototyping with Rails

I originally come from the java world. Setting up a new project got easier over the years but it is no comparison on what rails can do. Most blog posts I read when I started learning rails were about scaffolding. Scaffolding is a fast and easy way to create CRUD model/controller/view from scratch.

I usually do not use scaffolding in my working projects anymore, because they usually create a big overhead, but I just love that feature when it comes to a rapid prototype. A first version of our tutorize.com website was created in rails. It was not beautiful, not secure and not even close to be finished, but we had something to show to investors and possible customers. Lot of startup authors say that is the approach that works best for creating businesses without spending lots of money and time and then creating something that nobody even cares about. And I completely agree with it!

Ruby is easy to learn

I just have to say this: Ruby is a quite elegant language. If you have not tried it yet, try it. And the Rails framework is just

Rails code is easy to read because of the given structure

Rails comes with a given MVC-Pattern structure. It is really easy for other developers to dig into someone elses code because of that structure. You know where you find your models, your controllers and views and you know where the urls are build, etc. Very helpful!

And there is also the given structure of the rails engines. I started working with them a while ago and I can also say that this structure helps to understand the code of someone elses engine.

There are lots of features that I could take about right now, but I will leave some space for more posts to come. So try rails and keep on reading.