Skip to content

Instantly share code, notes, and snippets.

@dmitriy-kiriyenko
Created September 26, 2017 11:26
Show Gist options
  • Select an option

  • Save dmitriy-kiriyenko/46b94b453f06add29b3cd29a6a12a2c2 to your computer and use it in GitHub Desktop.

Select an option

Save dmitriy-kiriyenko/46b94b453f06add29b3cd29a6a12a2c2 to your computer and use it in GitHub Desktop.
Case Insensitive Active Record
module ActiveRecordHelpers
extend ActiveSupport::Concern
included do
scope :ci_where, ->(attrs) {
t = arel_table
attrs.reduce(self) do |rel, (name, value)|
rel.where(t[name].matches(value.strip))
end
}
end
class CiUniquenessValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
relation = record.class.ci_where(attribute => value)
relation = relation.where.not(id: record.id) if record.persisted?
relation = ci_scope.reduce(relation) do |rel, col|
rel.ci_where(col => record[col])
end
relation = scope.reduce(relation) do |rel, col|
rel.where(col => record[col])
end
record.errors.add(attribute, :taken) if relation.exists?
end
private
def scope
Array.wrap(options[:scope])
end
def ci_scope
Array.wrap(options[:ci_scope])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment