I generated the default devise views with:
rails generate devise:views
Then I added a username
field to the views/devise/registrations/new.html.erb
form.
Currently, only email
and password
validation occurs. How do I validate presence and uniqueness of the username
field? Do I need to add something to the User
model?
I used both the of the tutorials mentioned in the other answers, Railscast #210 and the Devise Wiki. However, so far as I could tell they do not explicitly say how to validate the presence and/or uniqueness of the username field.
If you added username with a simple migration -
rails generate migration addUsernameToUser username:string
Then devise doesn't do anything special with that field, so you need to add checks for validation and uniqueness yourself in the User model.
class User < ActiveRecord::Base
...
validates_presence_of :username
validates_uniqueness_of :username
However, If you look at the RailsCast #209 there is an example of the migration used to create the User model.
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.database_authenticatable :null => false
# t.confirmable
t.recoverable
t.rememberable
t.trackable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
t.timestamps
end
add_index :users, :email, :unique => true
# add_index :users, :confirmation_token, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :unlock_token, :unique => true
end
def self.down
drop_table :users
end
end
Notice here that the users email is defined as being unique. Perhaps if username was added using this same syntax then devise magic would take care of presence and uniqueness.
Rails 4 and Strong Parameters
On top of the above I had to generate the views with:
$ rails g devise:views
then in devise.rb
add:
config.scoped_views = true
and finally configure the permitted parameters as below for sign_up
as below:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit :username, :email, :password, :password_confirmation
end
end
end
This is described in Devise Doc
Also, my validation for username
is the following:
validates :username, presence: true
validates :username, uniqueness: true, if: -> { self.username.present? }
I use two lines, so if username
is blank I get only one error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With