Question

I need a help

I'm using simple form for select box. The code is here: = f.input :dogs, collection: (0..7). When render on browser, it will display select box with value from 0 to 7. I want add text behind value when select box dropdown. Eg: 1 dog - 2 dogs. I tried but not work.

Pls help me

Was it helpful?

Solution

You can use something like the following:

= f.input :dogs, options_for_select([["1 dog", 1], ["2 dogs", 1]])


= f.input :dogs, options_for_select((1..8).map{|x| x==1?  ["#{x} dog",x] : ["#{x} dogs",x] })

OTHER TIPS

A really simple and elegant solution could be something like this:

Create a helper method:

def humanize_dogs
  0.upto(7).each_with_object({}) { |c, h| h[pluralize(c, 'dog')] = c }
end
# => {"0 dogs"=>0, "1 dog"=>1, "2 dogs"=>2, "3 dogs"=>3, "4 dogs"=>4, "5 dogs"=>5, "6 dogs"=>6, "7 dogs"=>7}

In your form add the next line:

= f.input :dogs, collection: humanize_dogs

This generates...

<select id="#" name="#">
  <option value=""></option>
  <option value="0">0 dogs</option>
  <option value="1">1 dog</option>
  <option value="2">2 dogs</option>
  <option value="3">3 dogs</option>
  <option value="4">4 dogs</option>
  <option value="5">5 dogs</option>
  <option value="6">6 dogs</option>
  <option value="7">7 dogs</option>
</select>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top