Rails select helper - Default selected value, how?

后端 未结 15 1500
臣服心动
臣服心动 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:29

    Use the right attribute of the current instance (e.g. @work.project_id):

    <%= f.select :project_id, options_for_select(..., @work.project_id) %>
    
    0 讨论(0)
  • 2020-11-29 16:30

    This should do it:

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

    The problem with all of these answers is they set the field to the default value even if you're trying to edit your record.

    You need to set the default to your existing value and then only set it to the actual default if you don't have a value. Like so:

    f.select :field, options_for_select(value_array, f.object.field || default_value)
    

    For anyone not familiar with f.object.field you always use f.object then add your field name to the end of that.

    0 讨论(0)
  • 2020-11-29 16:37

    I've found solution and I found that I'm pretty unexperienced in RoR.

    Inside the controller that manages view described above add this:

    @work.project_id = params[:pid] unless params[:pid].nil?
    
    0 讨论(0)
  • 2020-11-29 16:39

    I couldn't get this to work and found that I needed to add the "selected" html attribute not only to the correct <option> tag but also to the <select> tag. MDN's docs on the selected attribute of the select tag say:

    selected - Boolean attribute indicates that a specific option can be initially selected.

    That means the code should look like:

    f.select :project_id, options_for_select(@project_select, default_val), html: {selected: true}
    
    0 讨论(0)
  • 2020-11-29 16:41

    If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)

    logger.warn("f #{f.object.inspect}")
    

    so, use the following script to get the proper selected option:

    :selected => f.object.your_field 
    
    0 讨论(0)
提交回复
热议问题