John Cowan
John Cowan

Reputation: 1684

Rails Form_For: How to Show Selected Value from Array in Update Form

I have another form_for select question. I'm using a partial for my new and edit form for my Customer model. The :customer_type can be one of three values: Contractor, Business, Homeowner. So, I put these values in an array in my model.

def self.customer_types 
  customer_types = ['Contractor', 'Homeowner', 'Business']
end

In my form I do this:

<%= f.select(:customer_type, options_for_select(Customer.customer_types)) %>

This works fine in the new form, but on the edit form, how do I get the selected value for :customer_type to be selected? I've tried several things but nothing works for me.

Thanks for any tips. -jc

Upvotes: 0

Views: 1758

Answers (1)

Tadas T
Tadas T

Reputation: 2637

options_for_select takes an optional second argument, which is the selected option :)

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select

The second thing you need is the actual value, which can be accessed via f.object. So something along those lines

<%= f.select(:customer_type, options_for_select(Customer.customer_types, f.object.customer_type)) %>

Upvotes: 3

Related Questions