Rails: Validating Your Models

Rails is all about patterns and when you're creating models, it's important to set pattern-based rules before you publish to your database. Below are simply a few pattern categories and I'll continue to add more over time.


Uniqueness Of

Validates the uniqueness of a field.

# Artists must have a unique name
validates :name, uniqueness: true

Presence Of

Validates the presence of data.

validates :title, presence: true

Format Of

Validate the format of an e-mail.

validates_format_of :email,:with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

Associated To

Validates associated

validates_associated :songs, :albums, :tracks