Skip to content

Instantly share code, notes, and snippets.

@npj
Created May 4, 2012 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npj/2596235 to your computer and use it in GitHub Desktop.
Save npj/2596235 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment