Hashes for select

by

In Ruby on Rails there’s a very easy way to create a select tag:

form.select("period", [["Month", 1], ["Year", 12]])

In my case I have the options in a hash, like:

periods = {
  1 => "Month",
  12 => "Year"
}

but when I did this:

form.select("period", periods)

I was surprised to find out that the keys of the hash are used as the content of the options, and the values as the keys, producing this code:

<select id="resource_period" name="resource[period]">
  <option value="Month">1</option>
  <option value="Year">12</option>
</select>

Definitely not what I wanted, so I wrote this method:

class ApplicationController < ActionController::Base
  helper_method :hash_for_select

  def hash_for_select(hash, sort_by = :value)
    sort_by = sort_by == :value ? 0 : 1
    options = hash.map { |k, v| [v, k] }.sort { |x, y| x[sort_by]  y[sort_by] }
  end

and now I can do

form.select("period", hash_for_select(periods))

if I want the options sorted by key value or

form.select("period", hash_for_select(periods, :key))

if I want them sorted by keys.


One response to “Hashes for select”

  1. Lasse Bunk Avatar

    I’d think that a better way would be:

    periods = {
    “Month” => 1,
    “Year” => 12
    }

    Because Month and Year are the keys, and 1 and 12 are the values.

Leave a Reply

You may also like:

Hi, I'm Pablo, this is my web site. You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 4,048 other subscribers

I'm writing a book

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I've been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Keep on Posting Kubuntu Lisp Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek startups technology Ubuntu web WordPress

I've been writing for a while:

%d bloggers like this: