Rails 3: f.select - options_for_select

2019-03-09 17:05发布

I have a form on my Ruby on Rails3 Application with a drop menu, this is my current code for the select option:

<%= f.select :phone_type, options_for_select(["Select One", "Cell", "Work", "Office", "Home", "Other"],:disabled => ["Select One"]), :class => 'genForm_dropBox' %>

From my understanding this should have "Select One" as the default option when someone opens the page, but if they don't select one of the other options an error displays when they hit submit.

This is true in Browsers like Safari and Chrome and IE7, but in Firefox and IE8 it shows "Cell" as the first option as Select One is disabled.

I'd like it to display "Select One" by default, but have it as an unusable option when they submit the form. Do I need to script this into the controller, or model? or do I have this coded in the form wrong?

6条回答
欢心
2楼-- · 2019-03-09 17:16

could be <%= f.select :phone_type, options_for_select(["Cell", "Work", "Office", "Home", "Other"]), :prompt => "Select One", :class => 'genForm_dropBox' %>

查看更多
聊天终结者
3楼-- · 2019-03-09 17:17

In Rails 4, this approach works well for me.

<%= f.select :status, options_for_status, {}, prompt: 'Select One' %>

Meanwhile I have defined the options in a helper to keep the clutter out of my view.

def options_for_status
  [
    ['First Option','first_option'],
    ['Second Option','second_option']
  ]
end
查看更多
女痞
4楼-- · 2019-03-09 17:23

for those looking to incorporate this feature, I've taken a new approach from the model end of things. Being that all fields are required to be filled out in order for the user to submit and not receive an error alert, I gave the "Submit One" option a default value of nothing. You can take a look at the following code to see how I did that.

<%= f.select :phone_type, options_for_select([["Select One", ""], "Cell", "Work", "Office", "Home", "Other"]), :class => 'genForm_dropBox' %>
查看更多
欢心
5楼-- · 2019-03-09 17:29

Adding the ["Select One", ""] causes the edit screen to alway display "Select One" rather than the stored value. Rails 3.1 (2012 Aug 17)

查看更多
家丑人穷心不美
6楼-- · 2019-03-09 17:32

This is a little cleaner:

<%= f.select :phone_type, [ 'Cell', 'Work', 'Office', 'Home', 'Other' ], :prompt => 'Select One' %>

The :prompt argument generates an option with an empty value.

查看更多
Explosion°爆炸
7楼-- · 2019-03-09 17:33

Thanks to everyone who contributed an answer.

I needed similar code for a project I'm working on and I really liked the approach Ryan Burnette took.

This is what worked for me using Rails 4.1.0.

<%= f.select :season, options_for_seasons, :prompt => 'Select One' %>

Then I defined the options in my helper.

def options_for_seasons
  ['Spring', 'Summer', 'Autumn', 'Winter']
end

I went with:prompt => 'Select One'because I only wanted the "Select One" option to be listed in the edit form if a season had not been previously selected.

查看更多
登录 后发表回答