Class: ClientSideValidations::ActiveRecord::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/client_side_validations/active_record/middleware.rb

Class Method Summary collapse

Class Method Details

.is_unique?(klass, attribute, value, params) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/client_side_validations/active_record/middleware.rb', line 4

def self.is_unique?(klass, attribute, value, params)
  column = klass.columns_hash[attribute.to_s]
  value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if column.text?

  t = klass.arel_table

  if params[:case_sensitive] == 'true'
    relation = t[attribute].eq(value)
  else
    relation = t[attribute].matches(value)
  end

  relation = relation.and(t[:id].not_eq(params[:id])) if params[:id]

  (params[:scope] || {}).each do |key, value|
    relation = relation.and(t[key].eq(value))
  end

  !klass.where(relation).exists?
end