【问题标题】:Validating the presence only if other simple_form field equals certain input?仅当其他 simple_form 字段等于某个输入时才验证存在?
【发布时间】:2020-03-13 17:50:30
【问题描述】:

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

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

表格

<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>

【问题讨论】:

  • 您是在询问服务器端验证吗?在这种情况下,您可以只使用带有 lambda 的 if: 选项。 validates_presence_of :apply_on, if: -&gt;{ discount_type == 'percent' }。不过,我会使用 ActiveRecord::Enum 作为折扣类型。
  • 嗨,Max,非常感谢。有效。对枚举的好评,认为这确实会使事情变得更高效/可扩展。
  • 如果您想自己回答问题,请随意使用它。

标签: jquery ruby-on-rails activerecord simple-form


【解决方案1】:

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

validates_presence_of :apply_on, if: ->{ discount_type == 'percent' }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2018-10-10
    • 2013-06-24
    相关资源
    最近更新 更多