Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Last active August 29, 2015 14:04
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 rob-murray/ed7da9b3f5d57702aab0 to your computer and use it in GitHub Desktop.
Save rob-murray/ed7da9b3f5d57702aab0 to your computer and use it in GitHub Desktop.
Validate that a `Page` does not have any siblings with the same `:slug`
class MatchingPageSlugValidator < ActiveModel::Validator
def validate(record)
# Ancestry gem #siblings includes current record, exclude this if present
exclude_self = record.try(:id) ? ['id <> ?', record.id] : []
sibling_slugs = record.siblings.where(exclude_self).pluck(:slug)
if sibling_slugs.include?(record.slug)
record.errors[:slug] << 'belongs to another page at this level.'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment