Created
September 26, 2017 11:26
-
-
Save dmitriy-kiriyenko/46b94b453f06add29b3cd29a6a12a2c2 to your computer and use it in GitHub Desktop.
Case Insensitive Active Record
This file contains hidden or 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
| 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