I have a simple Ruby on Rails application with Devise for authentication. I would like users to register using a username instead of email and try to implement this as described here:
Invent authentication with a username instead of email
The twist is that I still want every user to have an email address and require it during registration. So, I left the "email" field in the registration form.
The problem is that when I fill out the registration form using a valid email address (or any other email value), Devise reports the error: "Email cannot be empty."
Why is email considered blank and how can I fix it?
class ApplicationController < ActionController::Base
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) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :password, :remember_me) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password) }
end
end
User model
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Type for registration
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<div class="field">
<%= f.label :username %><br />
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :password %>
<% if @validatable %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
devise.rb modified to include:
config.authentication_keys = [ :username ]
This is displayed in the rails server console when submitting the form:
Started POST "/users" for ::1 at 2015-03-17 14:29:13 -0700
Processing by Devise::RegistrationsController
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bc5+ffyBSr6h79aumdMpwHhp5OY69
Tk5oKyY+eIBHLCDDwPmxiMbjbE6OTIaeUPGLmS0J+QlwlGFGHki8SKsgA==", "user"=>{"email"=>
"jessa@example.com", "username"=>"Jessa", "password"=>"[FILTERED]", "password_co
nfirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameter: email
(0.0ms) BEGIN
(0.0ms) ROLLBACK
Rendered devise/shared/_links.html.erb (2.0ms)
Rendered devise/registrations/new.html.erb within layouts/application (11.0ms)
I see Unpermitted parameter: email, but don’t know how to fix it.