Skip to content
Create a gist now

Instantly share code, notes, and snippets.

# 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
Something went wrong with that request. Please try again.