In my simple_form a user can select a discount_type
. With JQuery, the apply_on
field is hidden when the DOM is loaded and only shows when the discount_type
percent is selected.
Issue:
I only want to validate the presence for apply_on
when discount_type
percent
is selected, but I don't know how/where to do this?
form
<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>
As per Max' answer, I can add the following to the discount model:
validates_presence_of :apply_on, if: ->{ discount_type == 'percent' }