Rails 3: f.select - options_for_select

前提是你 提交于 2019-12-02 17:29:27

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' %>

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.

rb-

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

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!