Skip to content

Instantly share code, notes, and snippets.

@PragmaticEd
Last active June 14, 2018 12:26
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 PragmaticEd/b1f436f9578f5288d4842fc06b43c668 to your computer and use it in GitHub Desktop.
Save PragmaticEd/b1f436f9578f5288d4842fc06b43c668 to your computer and use it in GitHub Desktop.
Globalize gem uniqueness validation
# 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