[ruby on rails]devise只使用username注册登陆

1.添加gemcss

gem 'devise'

2.安装devisehtml

rails generate devise:install

3.添加相关配置web

#config/environments/development.rb

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
#routes.rb

root 'xxx#xxx'
#application.html.erb     这里结合了bootstrap使用

<% if flash.any? %>
<% flash.each do |message_type,message| %>
    <div class="alert alert-<%= message_type %>" >
   		<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    	<%= message %>
    </div>
 <% end %>
 <% end %>
#application.scss

@import "bootstrap-sprockets";
@import 'bootstrap';
 .alert-notice{
   @extend .alert-success;
 }
 .alert-alert{
   @extend .alert-danger;
 }

4.生成user模型bootstrap

rails generate devise user
rails db:migrate

5.在须要使用的controller里使用session

before_action :authenticate_user!
  • 只用username注册登陆,不用email

1.使用username做为验证关键字app

#config/initializers/devise.rb

config.authentication_keys = [:username]

2.添加惟一性验证svg

#user.rb

validates :username, uniqueness: true

3.添加username字段和惟一索引ui

rails generate migration add_username_to_users username:string:uniq

4.去掉email惟一索引,这样email就能够重复this

rails g migration remove_email_index_from_users

#remove_email_index_from_users.rb

 def change
    remove_index :users, :email
 end

5.strong parametersurl

#application_controller.rb

  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
    devise_parameter_sanitizer.permit(:sign_in, keys: [:username])
  end

6.修改页面

rails g devise:views
#app/views/devise/sessions/new.html.erb
#app/views/devise/registrations/new.html.erb

将email改成username

7.修改错误提示

#config/locales/devise.en.yml

invalid: 'Invalid email or password.'
not_found_in_database: 'Invalid email or password.'

改成:

invalid: 'Invalid username or password.'
not_found_in_database: 'Invalid username or password.'

若是是下面的就不用改了

invalid: "Invalid %{authentication_keys} or password."
not_found_in_database: "Invalid %{authentication_keys} or password."

8.将email必须存在去掉

#user.rb
 
 def email_required?
    false
  end

  def email_changed?
    false
  end
  
  # use this instead of email_changed? for Rails = 5.1.x
  def will_save_change_to_email?
    false
  end