Rails options_for_select with include blank and selected option

If you want to use a select_tag and include a blank option it can be achieved using the following snippet:

<%= select_tag “district”, options_for_select(Customer.all.collect { |k| ["#{k.district} #{k.store}", k.id] }.insert(0, ["", 0]), params[:number].to_i) %>

- it also handles setting the selected option if one is passed – in this case in the query string. I have been blogging about this previously but noticed that I had forgotten to show how to pass the chosen option if one exists.

options_from_collection_for_select with selected options

When you have been working with Rails for a while, you start too seek the quick solutions when writing code, it’s what you expect from Rails and Ruby, the solution should be rigth there, but sometimes you need just a little more code to accomplish what your looking for, like when you want to populate a options_from_collection_for_select with selected options. Continue reading

Follow

Get every new post delivered to your Inbox.