Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Movie < ActiveRecord::Base
- RATINGS = %w[G PG PG-13 R NC-17] # %w[] shortcut for array of strings
- validates_presence_of :title
- validates_inclusion_of :rating, :in => RATINGS
- validate :released_1930_or_later # uses custom validator below
- def released_1930_or_later
- # 'self' is the object being validated
- errors.add(:release_date, 'must be 1930 or later') if release_date < Date.parse('1 Jan 1930')
- 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] # => ["is not included in the list"]
- m.errors[:release_date] # => ["must be 1930 or later"]
- m.errors.full_messages # => ["Title can't be blank", "Rating is not included in the list", "Release date must be 1930 or later"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement