Skip to content

Instantly share code, notes, and snippets.

@borisd
Created January 16, 2014 10:09
Show Gist options
  • Save borisd/8452549 to your computer and use it in GitHub Desktop.
Save borisd/8452549 to your computer and use it in GitHub Desktop.
Solution to ActiveRecord Validations homework
class Cat < ActiveRecord::Base
attr_accessible :birthdate, :breed, :name
BREEDS = [:arabean, :asian, :bengal, :persian]
# Name must be present and between 5 and 20 characters
validates :name, length: { in: 5..20 }
# Breed must be one of the following: :arabean, :asian, :bengal, :persian
validates :breed, inclusion: { in: BREEDS }
# Birthdate must be after 'today' (Date.today) and cat must not be older than 20 years.
validate :valid_birthdate
def valid_birthdate
if birthdate
errors.add(:birthday, "Must be in the past") if birthdate > Date.today
errors.add(:birthday, "Age must be below 20 years") if birthdate < 20.years.ago
end
end
# Valid cat:
# Cat.create! name: 'Kipod', breed: :persian, birthdate: 3.years.ago
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment