Rails select options

written by justin on August 24th, 2007 @ 03:48 PM

I am developing an application where I have a dropdown list of hours worked on a project. The spec is that it should be in quarter hour increments using a decimal notation. So, 0, 0.25, 0.50, 0.75, etc. The select helper in rails takes an array of arrays that would look like this: [[0,0],[.25,.25], etc...]. I needed to generate that array and this is what I came up with:

  def labor_hours
    ar = []
    (0..39).each do |n| 
    	a = n.to_f
    	b = a + 0.25
    	c = a + 0.50
    	d = a + 0.75
    	ar.push([sprintf('%0.2f', a), a],[sprintf('%0.2f', b), b],[sprintf('%0.2f', c), c],[sprintf('%0.2f', d), d])
    end
    ar.push(["40.00",40])
  end

I start by creating the array that I'm going to return. I then use a range and a block to loop over 0 to 39. I have to made sure that I convert the integers to floats and add my partial hours. I then create my arrays for this integer and add them to the final array. At the last second, I add the last array for a nice even 40 hours. Works pretty well. I used sprintf to format the floats so that everything has 2 decimal places instead of some with one and some with two.

So, my view code looks like this:

<%= form.select 'labor', labor_hours, :include_blank => true %>

Comments

  • Cezar on 14 Feb 20:01

    How about make ar into @ar and provide that to select ?
  • Justin on 16 Feb 08:12

    You could certainly do that, but the way I have it set up, it is in a helper module, so it would need to get moved somewhere that it could be called from the controller.
  • moe on 02 Sep 22:05

    Putting it in the helper class is the best way to go. For example, I always write a quick function for selecting genders. #Helper def gender_select [ [ 'Male', 'Male'], [ 'Female','Female'] ] end #View <%= select :member, :gender , gender_select %> I just wrote a blog on the Rails Select Helper. If you get a chance check it out and let me know what you think. http://badpopcorn.com/blog/2008/09/02/rails-select-helper/

Post a comment