Tag: templates

  • 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.