@@ -5,7 +5,7 @@ class Item < ApplicationRecord
55 validates :name , uniqueness : { scope : :category_id , message : "Item name must be unique within category" }
66 validate :category_must_be_active
77 validate :fixed_parameters_values_must_be_numeric
8- # validate :pricing_options_values_must_be_numeric
8+ validate :pricing_options_values_must_be_numeric
99 validates :calculation_formula , presence : true , if : :requires_calculation_formula?
1010
1111 def self . ransackable_attributes ( _auth_object = nil )
@@ -29,26 +29,29 @@ def fixed_parameters_values_must_be_numeric
2929 end
3030
3131 def pricing_options_values_must_be_numeric
32- validate_jsonb_numeric_values ( :pricing_options )
32+ validate_jsonb_numeric_values ( :pricing_options ) do |key_path , val |
33+ key_path . last != 'value_label' && !numeric? ( val )
34+ end
3335 end
3436
35- def validate_jsonb_numeric_values ( attribute )
37+ def validate_jsonb_numeric_values ( attribute , & block )
3638 value = self [ attribute ] || { }
3739 unless value . is_a? ( Hash )
3840 errors . add ( attribute , "must be a JSON object" )
3941 return
4042 end
4143
42- validate_nested_numeric_values ( value , attribute )
44+ validate_nested_numeric_values ( value , attribute , [ ] , & block )
4345 end
4446
45- def validate_nested_numeric_values ( hash , attribute , key_path = [ ] )
47+ def validate_nested_numeric_values ( hash , attribute , key_path = [ ] , & block )
4648 hash . each do |key , val |
4749 current_path = key_path + [ key ]
4850 if val . is_a? ( Hash )
49- validate_nested_numeric_values ( val , attribute , current_path )
51+ validate_nested_numeric_values ( val , attribute , current_path , & block )
5052 else
51- errors . add ( attribute , "value for '#{ current_path . join ( ' -> ' ) } ' must be a number" ) unless numeric? ( val )
53+ should_error = block_given? ? yield ( current_path , val ) : !numeric? ( val )
54+ errors . add ( attribute , "value for '#{ current_path . join ( ' -> ' ) } ' must be a number" ) if should_error
5255 end
5356 end
5457 end
0 commit comments