Question

I have something like:

class User
  include DataMapper::Resource

  property :id, Serial
  property :username, String, :unique => true
end

post '/signup' do
  user = User.create(username: params['username'])
  if user.save
    puts "New user was created"
  else
    puts user.errors
  end
end

Parameter :unique => true is case-sensitive. It does not prevent to create users with usernames 'admin' and 'Admin'. How can I validate case-insensitive username unique, with out downcased username property, so users can make usernames as they choose.

Was it helpful?

Solution

You can provide your own custom validation:

class User
  include DataMapper::Resource

  property :id, Serial
  property :username, String

  validates_with_method :username,
                        :method => :case_insensitive_unique_username

  def case_insensitive_unique_username
    User.first(conditions: ["username ILIKE ?", self.username]).nil?
  end
end

Note that ILIKE will only work with PostgreSQL, you will have to find out how to find records case insensitively with your specific adapter for yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top