Ruby on Rails: Validations May 4th, 2015

  • Validations are used to ensure that only valid data is saved into your database
    • Model-level validations are the best way
      • They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain
    • If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation
  • Validations are triggered by the methods create, create!, save, save!, update, and update!
    • The bang versions (e.g. save!) raise an exception if the record is invalid
    • The non-bang versions don’t, save and update return false, create just returns the object
  • To verify whether or not an object is valid, Rails uses the valid? method
  • The errors method can be run after validations
  • Helper methods
    • acceptance … validates a checkbox and can be a virtual attribute not stored in the database
    • validates_associated … when your model has associations with other models which also need validation
      • Don’t call on both ends or you’ll get an infinite loop
    • confirmation … when two fields must match
    • exclusion … validates that the attributes’ values are not included in a given set
    • format … to match a regex
    • inclusion … validates that the attributes’ values are included in a given set
    • length … {minimum: 10}, {maximum: 500}, {in: 6..20}, {is: 2}
    • numericality … validates that your attributes have only numeric values
      // e.g.
      numericality: true
      numericality: { only_integer: true }
    • presence … to make sure it’s not empty
    • absence … to make sure it’s empty
    • uniqueness …This helper validates that the attribute’s value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index on both columns in your database
    • validates_with … to pass the record to a separate class for validation
    • validates_each … to validate attributes against a block
    • allow_nil
    • allow_blank
    • message … for error message
    • on … for when the validation should happen
    • Conditional validation with if or unless (e.g. validates :card_number, presence: true, if: :paid_with_card?)

Resources