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

1.添加gem

gem 'devise'

2.安装devise

 rails generate devise:install

3.添加相关配置

#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| %>
    
<%= message %>
<% end %> <% end %>
#application.scss

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

4.生成user模型

rails generate devise user
rails db:migrate

5.在需要使用的controller里使用

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

1.使用username作为验证关键字

#config/initializers/devise.rb

config.authentication_keys = [:username]

2.添加唯一性验证

#user.rb

validates :username, uniqueness: true

3.添加username字段和唯一索引

rails generate migration add_username_to_users username:string:uniq

4.去掉email唯一索引,这样email就可以重复

rails g migration remove_email_index_from_users

#remove_email_index_from_users.rb

 def change
    remove_index :users, :email
 end

5.strong parameters

#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

你可能感兴趣的:(ruby,on,rails)