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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

the dojo

twits

RSS Fork me…

  • An error has occurred; the feed is probably down. Try again later.
Follow

Get every new post delivered to your Inbox.