Models: Callbacks and Validations

class User < ApplicationRecord
  validates :name, presence: true
  validates :name, length: { maximum: 20 }
  validates :password, length: { in: 6..20, message: "%{value} is not valid"  }
  validates :email, confirmation: true # Adds tmp attr email_confirmation

  has_many :books, :dependent => :destroy
  validates_associated :books #if has_many :books association
 
  before_save :ensure_login_has_a_value, if: :some_test?
  after_validation :set_location, on: [ :create, :update ]
  
  scope :published, -> { where(published: true) }
 
 
  private
    def ensure_login_has_a_value
      if login.nil?
        self.login = email unless email.blank?
      end
    end
end
Comments