根据 rails 中另一个下拉列表的值生成下拉值

Generating dropdown values based on value of another dropdown in rails

所以基本上,我要做的是在 bug_type 下拉列表的值为 bug 时将状态下拉列表的值显示为 [initial, started completed],否则状态下拉列表应显示 [initial, started,已解决]

<div class="col">
  <div class="form-group">
    <%= form.select :bug_type, options_for_select([['Bug', 'bug'], ['Feature', 'feature']]) %> <br>
  </div>
</div>

<div class="col">
  <div class="form-group">
    <% if @bug.bug_type == 'bug'%>
      <%= form.select :status, options_for_select([['Initial', 'initial'], ['Started', 'started'], ['Completed', 'completed']]) %> <br>
    <% else %>
      <%= form.select :status, options_for_select([['Initial', 'initial'], ['Started', 'started'], ['Resolved', 'resolved']]) %> <br>
    <% end %>
  </div>
</div>

到目前为止,我尝试过这样做,但它不起作用。 此外,我还为 bug_type 和状态使用了枚举。如果有其他方法可以解决这个问题,请帮助我。

有两种方法可以满足您的要求。一种是客户端,您可以更改下拉值,或者您可以发送一个服务器端请求并呈现您需要的选项。

对于客户端你可以这样做:

<div class="col">
  <div class="form-group">
    <%= form.select :bug_type, options_for_select([["Bug", "bug"], ["Feature", "feature"]]) %>
  </div>
</div>

<div class="col">
  <div class="form-group">
    <% if @bug.bug_type == "bug" %>
      <%= form.select :status, options_for_select([["Initial", "initial"], ["Started", "started"], ["Completed", "completed"]]) %>
    <% else %>
      <%= form.select :status, options_for_select([["Initial", "initial"], ["Started", "started"], ["Resolved", "resolved"]]) %>
    <% end %>
  </div>
</div>

<script>
  // Please change selector accoding to your DOM.
  // This is bug type select dropdown
  $('#bug_type_select').change(function() {
    var selectedValue = $('#bug_type option:selected').val();
    var bugOptions = {
      'initial': 'Initial',
      'started': 'Started',
      'completed': 'Completed'
    }

    var featureOptions = {
      'initial': 'Initial',
      'started': 'Started',
      'resolved': 'Resolved'
    }

    // Please change selector accoding to your DOM.
    // This is status select dropdown
    var $mySelect = $('#mySelect');
    $mySelect.empty();

    if (selectedValue === 'bug') {
      $.each(bugOptions, function(key, value) {
        var $option = $('<option/>', {
          value: key,
          text: value
        });

        $mySelect.append($option);
      });
    } else {
      $.each(featureOptions, function(key, value) {
        var $option = $('<option/>', {
          value: key,
          text: value
        });

        $mySelect.append($option);
      });
    }
  });
</script>