简体   繁体   中英

Ruby on rails: Select options menu with default value attribute

I need to produce a select menu with a Default value on the list of <options> . Here is how I need it looks like.

<select name="menu[parent_id]" id="menu_parent_id">
 <option value="0">==None==</option>
 <option value="34">TEST</option>
</select>

Currently I use this select helper in my form

   <%= f.select(:parent_id, @parent_menus.collect {|p| [ p.name, p.id ] }, {:include_blank => '==None=='})%>

the above code produce this; ( value="" )

<select name="menu[parent_id]" id="menu_parent_id">
 <option value="">==None==</option>
 <option value="34">TEST</option>
</select>

Does anyone here can show me a way to add value="0" to the options list?

<%= f.select(:parent_id, [["==None==", 0]] + @parent_menus.collect {|p| [ p.name, p.id ] }) %>

Thought I would add this to anyone looking to do a default selected value that is one of the objects in the dropdown , as opposed to a 'none' value. ie, you are editing a form that has a previous value selected, and you don't want to lose that previous value on your edit page:

Assuming you have an array of parents held in @parents and your form is tied to an object called @my_messed_up_family, and @my_messed_up_family has one 'father':

= f.label :parent_id, "Choose which of your parents is your father?

= f.select :parent_id, options_from_collection_for_select(@parents.sort_by {|n| n.name}, "id", "name", :selected=>@my_messed_up_family.father.id)

尝试

<%= f.select(:parent_id, options_for_select(["==None==", 0] + @parent_menus.collect {|p| [ p.name, p.id ] }, 0)) %>

I don't know this is Ruby way or not But this will definietly work

<%= f.select(:parent_id, "<option value='0'>Please select</option>"+options_for_select(@parent_menus.collect {|p| [ p.name, p.id ] }))%>

EDITED. For pre-selected according to the value save in database i assume @user is your object contain the database value for following example.

<%= f.select(:parent_id, "<option value='0'>Please select</option>"+options_for_select(@parent_menus.collect {|p| [ p.name, p.id ] }, @user.id ))%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM