ActiveRecord getter authentication

I need to verify my credit card number.

model Billing
  validates :card, credit_card_number: true, allow_nil: true

Valid Jewel 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 is working fine. But then I try to override geter like this:

   def card
    "****#{self[:card][-4,4]}" if self[:card]
   end

Verification failed. when i monkey fixed validates_each like this:

  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

He came back to work well. This is the correct validation behavior to validate getters instead of constant values ​​(validates_each first option follows the manual). Or what is the preferred way to solve my problem? Update: Activemodel / Activerecord Version: 4.2.3

+4
source share
2 answers

-, , , - . , , , , .

, :

def starred_card
  card && "****#{card[-4,4]}"
end
+1

getter ( ), .

, , nil , 16 .

validate :correct_credit_card_number

def correct_credit_card_number
    if self[:card] && self[:card] !~ /^\d{16}$/
        errors.add(:card, "is not in the right format")
    end
end
0

Source: https://habr.com/ru/post/1620541/


All Articles