仅当其他simple_form字段等于某些输入时才验证存在吗?

在我的simple_form中,用户可以选择discount_type。使用JQuery,在加载DOM时apply_on字段是隐藏的,仅在选择discount_type percent 时才显示。

问题: 我只想在选择apply_on discount_type时验证percent的存在,但是我不知道如何/在何处执行此操作?

表格

<div class="col col-sm-4"><%= f.input :discount_type,collection: ['percent','price'] %></div>
<div class="col col-sm-4 apply_on_percentage"><%= f.input :apply_on,collection: ['reservation total','accommodation total'],prompt: "Choose on what to apply the discount" %></div>

<script>
  // Hide form field when DOM is loaded
  $(document).ready(function(){
    $('.apply_on_percentage').hide();
  });

  // Load form field when percentage is selected
  $(document).on("change","#discount_discount_type",function(){
    var discount_type = $(this).val();
    if(discount_type === 'percent'){
      $('.apply_on_percentage').show();
    } else{
      $('.apply_on_percentage').hide();
    }
  });


</script>
shao__fei 回答:仅当其他simple_form字段等于某些输入时才验证存在吗?

根据Max的回答,我可以在折扣模型中添加以下内容:

validates_presence_of :apply_on,if: ->{ discount_type == 'percent' }
本文链接:https://www.f2er.com/3081655.html

大家都在问