Last active
June 14, 2018 12:26
-
-
Save PragmaticEd/b1f436f9578f5288d4842fc06b43c668 to your computer and use it in GitHub Desktop.
Globalize gem uniqueness validation
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
# Usage in model: | |
# | |
# validates :title, translation_uniqueness: true # will assume it must be uniq across all languages | |
# validates :title, translation_uniqueness: {scope: :locale, message: ''} | |
# | |
class TranslationUniquenessValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
record.translations.each do |t| | |
if options[:scope] == :locale | |
records = t.class.where("locale = '#{t.locale.to_s}' AND #{attribute} = '#{t[attribute]}'") | |
else | |
records = t.class.where("#{attribute} = '#{t[attribute]}'") | |
end | |
# on create | |
if record.id.nil? | |
record.errors.add("#{attribute}_#{t.locale}", options[:message] || :uniqueness) unless records.count.zero? | |
end | |
# on update | |
unless record.id.nil? | |
if records.count > 0 && !records.pluck(:city_id).include?(record.id) | |
record.errors.add("#{attribute}_#{t.locale}", options[:message] || :uniqueness) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment