Rails select helper - Default selected value, how?

后端 未结 15 1490
臣服心动
臣服心动 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:47
    <%= f.select :project_id, @project_select, :selected => params[:pid] %>
    
    0 讨论(0)
  • 2020-11-29 16:49

    Mike Bethany's answer above worked to set a default value when a new record was being created and still have the value the user selected show in the edit form. However, I added a model validation and it would not let me submit the form. Here's what worked for me to have a model validation on the field and to show a default value as well as the value the user selected when in edit mode.

      <div class="field">
        <%= f.label :project_id, 'my project id', class: "control-label" %><br>
        <% if @work.new_record? %>
          <%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], true), {}, required: true, class: "form-control" %><br>
        <% else %>
          <%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], @work.project_id), {}, required: true, class: "form-control" %><br>
        <% end %>
      </div>
    

    model validation

      validates :project_id, presence: true
    
    0 讨论(0)
  • 2020-11-29 16:50

    Alternatively, you could set the :project_id attribute in the controller, since the first argument of f.select pulls that particular attribute.

    0 讨论(0)
提交回复
热议问题