I am using devise for my rails app. I wanted to add the username field so I added a migration to the database. Now I want devise to validate the user_name field for uniqueness but I am not able to figure out how to do that. I also want it to show the error as it does with the default email field.
Asked
Active
Viewed 636 times
2 Answers
1
Just add validation for user_name
in User
model
validates :user_name, uniqueness: true

Rajdeep Singh
- 17,621
- 6
- 53
- 78
0
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
end
end
User Model code change - add validation
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :username , uniqueness: {case_sesitive: false}
end

PRN
- 231
- 2
- 5