Advertisement
saasbook

validation_example.rb

Feb 20th, 2012
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.85 KB | None | 0 0
  1. class Movie < ActiveRecord::Base
  2.   RATINGS = %w[G PG PG-13 R NC-17]  #  %w[] shortcut for array of strings
  3.   validates_presence_of :title
  4.   validates_inclusion_of :rating, :in => RATINGS
  5.   validate :released_1930_or_later # uses custom validator below
  6.   def released_1930_or_later
  7.     # 'self' is the object being validated
  8.     errors.add(:release_date, 'must be 1930 or later') if release_date < Date.parse('1 Jan 1930')
  9.   end
  10. end
  11. # try in console:
  12. m = Movie.new(:title => '', :rating => 'RG', :release_date => '1929-01-01')
  13. # force validation checks to be performed:
  14. m.valid?  # => false
  15. m.errors[:title] # => ["can't be blank"]
  16. m.errors[:rating] # => ["is not included in the list"]
  17. m.errors[:release_date] # => ["must be 1930 or later"]
  18. 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