vanderleipinto / preparation_mentorship

0 stars 0 forks source link

Validate CNPJ in Supplier #27

Closed vanderleipinto closed 9 months ago

vanderleipinto commented 9 months ago

Add Gem

Add gem 'cpf_cnpj' into the project. In the file Gemfile:

# Validator to CPF and CNPJ
gem 'cpf_cnpj', '~> 0.2.1'

Runs bundle to install the Gem

bundle

Add validates into the Supplier model including the callback validator 'validate_cnpj':

class Supplier < ApplicationRecord
  has_one :account

  has_many :parts, dependent: :destroy
  validates :name, presence: true
  validates :cnpj, presence: true, uniqueness: true

  validate :cnpj, :validate_cnpj

  private 

  def validate_cnpj
     errors.add(:cnpj, "invalid cnpj") unless CNPJ.valid?(cnpj)
  end

end