Rails select helper - Default selected value, how?

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

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

    model validation

      validates :project_id, presence: true
    

提交回复
热议问题