Skip to content

Instantly share code, notes, and snippets.

@armandofox
Created February 22, 2021 00:59
Show Gist options
  • Save armandofox/89adee067f097c7167e38e2c40a555aa to your computer and use it in GitHub Desktop.
Save armandofox/89adee067f097c7167e38e2c40a555aa to your computer and use it in GitHub Desktop.
validation_example.rb
class Movie < ActiveRecord::Base
def self.all_ratings ; %w[G PG PG-13 R NC-17] ; end # shortcut: array of strings
validates :title, :presence => true
validates :release_date, :presence => true
validate :released_1930_or_later # uses custom validator below
validates :rating, :inclusion => {:in => Movie.all_ratings},
:unless => :grandfathered?
def released_1930_or_later
errors.add(:release_date, 'must be 1930 or later') if
release_date && release_date < Date.parse('1 Jan 1930')
end
@@grandfathered_date = Date.parse('1 Nov 1968')
def grandfathered?
release_date && release_date < @@grandfathered_date
end
end
# try in console:
m = Movie.new(:title => '', :rating => 'RG', :release_date => '1929-01-01')
# force validation checks to be performed:
m.valid? # => false
m.errors[:title] # => ["can't be blank"]
m.errors[:rating] # => [] - validation skipped for grandfathered movies
m.errors[:release_date] # => ["must be 1930 or later"]
m.errors.full_messages # => ["Title can't be blank", "Release date
must be 1930 or later"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment