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.

You may also like:

If you want to work with me or hire me? Contact me

You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 5,047 other subscribers

I wrote 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 Kubuntu Lisp management 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 technology Ubuntu web Windows WordPress

I’ve been writing for a while:

Mastodon