Created
January 16, 2014 10:09
-
-
Save borisd/8452549 to your computer and use it in GitHub Desktop.
Solution to ActiveRecord Validations homework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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