Last active
August 29, 2015 14:04
-
-
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`
This file contains 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 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