public
Created

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# app/models/post.rb
class Post < ActiveRecord::Base
validate :ensure_slug_uniqueness
protected
# validate
def ensure_slug_uniqueness
# we also want to ensure the slug is not blank
if self.slug.blank?
errors.add(:slug, "can't be blank")
end
# if this is a new post, the id is nil
# otherwise, the slug should point to this post's id
unless Slug[self.slug].nil? || Slug[self.slug] == self.id.to_s
errors.add(:slug, "is already taken")
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.