Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord getter breaks validation

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

like image 252
Boris Kraportov Avatar asked Nov 09 '22 23:11

Boris Kraportov


1 Answers

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
like image 170
BroiSatse Avatar answered Nov 15 '22 04:11

BroiSatse