goddamnyouryan
goddamnyouryan

Reputation: 6896

Rails 3 Select Menu Default Value when editing an Entry

I am using the following code for a select menu in my rails app

Controller:

@discount_options = {'% Off' => 'percent', '$ Off' => 'dollar', '$ For' => 'flat', 'Free with Purchase Of' => 'bonus', 'Buy One Get One Free' => 'bogo' }

View (within a form_for)

<%= f.select :discount, options_for_select(@frugle_discount_options) %>

This works just fine when creating a new record. If I come back to edit this record, it always ends up defaulting to the first one "% Off"

I find it surprisingly hard to find good documentation online about select menus.. can someone help me out?

Thanks!

Upvotes: 4

Views: 2772

Answers (3)

gavit
gavit

Reputation: 509

You should make a reference to the f.object with :selected

    <%= f.select :discount, options_for_select(@frugle_discount_options), :selected => f.object.discount %>

Upvotes: 2

slm
slm

Reputation: 16416

Here's a great blog post I came across that discusses the use of the various select helpers in rails. Worth a read.

http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails

Upvotes: 1

Ashish
Ashish

Reputation: 5791

You can pass second parameter in

options_for_select_method(@discount_options, 'bonus')

You can set it by using :discount parameter.

Upvotes: 3

Related Questions