I need to validate credit card number.
model Billing
validates :card, credit_card_number: true, allow_nil: true
Validation gem code:
def validate_each(record, attribute, value)
record.errors.add(attribute, options[:message] || :invalid) unless credit_card_valid?(value, extract_brands(record, options))
end
It works ok. But then I try to override geter this way:
def card
"****#{self[:card][-4,4]}" if self[:card]
end
Validation fails. when I monkey patched validates_each like that:
def validate_each(record, attribute, value)
value = record[attribute]
record.errors.add(attribute, options[:message] || :invalid) unless credit_card_valid?(value, extract_brands(record, options))
end
It back to work well. Is it correct validation behavior, to validates getters instead of persisted values (validates_each first variant is follows guide). Or what is preffered way to solve my problem? Update: Activemodel/Activerecord version: 4.2.3
Firstly, the method you defined is not a model concern - it is a view concern and as such should be moved to a helper or presenter. This is however very common practice to have such methods within the model, so I wouldn't say that's a huge problem.
You can easily get around the whole problem, by picking the other name for your method:
def starred_card
card && "****#{card[-4,4]}"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With