Adding Custom Options to Rails Select Controls

Rails makes creating an HTML Select Control easy, but what about when you want to add custom options to the selection list? Also easy.  Let’s look at an example of a Select list with not one but two additional custom options.

We have a Store Selection so we can can assign coupons to a store. But we also want to add two additional options: “Manufacturer’s Coupon” at the top of the list and “Other” at the bottom.

On new coupons we want the default selection item to be “Manufacturer’s Coupon.”  The Manufacturer’s Coupon has an ID of -1 and here’s where we’ll set that in the controller.

Now for the HTML.  We’re going to invoke the { |s| [s.name, s.id] } block for each element of our stores array to generate our user’s stores using the Ruby collect() method.  Before and after the array we’re adding our custom options as nested arrays.

More Select Option goodness can be found on the RailsGuides Form Helpers page.