Rails select helper - Default selected value, how?

后端 未结 15 1489
臣服心动
臣服心动 2020-11-29 16:06

Here is a piece of code I\'m using now:

<%= f.select :project_id, @project_select %>

How to modify it to make its default value equal

相关标签:
15条回答
  • 2020-11-29 16:42

    Try this:

        <%= f.select :project_id, @project_select, :selected => f.object.project_id %>
    
    0 讨论(0)
  • 2020-11-29 16:43

    Rails 3.0.9

    select options_for_select([value1, value2, value3], default)
    
    0 讨论(0)
  • 2020-11-29 16:43

    if params[:pid] is a string, which if it came from a form, it is, you'll probably need to use

    params[:pid].to_i  
    

    for the correct item to be selected in the select list

    0 讨论(0)
  • 2020-11-29 16:43
    <%= f.select :project_id, options_from_collection_for_select(@project_select,) %>
    
    0 讨论(0)
  • 2020-11-29 16:43

    This should work for you. It just passes {:value => params[:pid] } to the html_options variable.

    <%= f.select :project_id, @project_select, {}, {:value => params[:pid] } %>
    
    0 讨论(0)
  • 2020-11-29 16:44

    Its already explained, Will try to give an example

    let the select list be

    select_list = { eligible: 1, ineligible: 0 }
    

    So the following code results in

    <%= f.select :to_vote, select_list %>
    
    <select name="to_vote" id="to_vote">
      <option value="1">eligible</option>
      <option value="0">ineligible</option>
    </select>
    

    So to make a option selected by default we have to use selected: value.

    <%= f.select :to_vote, select_list, selected: select_list.can_vote? ? 1 : 0 %>
    

    if can_vote? returns true it sets selected: 1 then the first value will be selected else second.

    select name="driver[bca_aw_eligible]" id="driver_bca_aw_eligible">
      <option value="1">eligible</option>
      <option selected="selected" value="0">ineligible</option>
    </select>
    

    if the select options are just a array list instead of hast then the selected will be just the value to be selected for example if

    select_list = [ 'eligible', 'ineligible' ]
    

    now the selected will just take

    <%= f.select :to_vote, select_list, selected: 'ineligible' %>
    
    0 讨论(0)
提交回复
热议问题