如果你像我一样刚开始学习Rails,则建议直接开始使用Rails 8.0.0.beta版本,因为该版本更新优化了很多功能,最重要的是加入了身份验证模块抽象层,不用像7之前的版本那样麻烦。
在这里记录下我的相关笔记
- 一键生成身份验证系统:
bin/rails generate authentication
该命令会创建User、Current、Session三个模型,并且会在app/controllers/conerns
下添加Authentication模块 - 只有认证模块,没有注册模块
- 默认使用邮箱和密码进行认证
- Authentication模块的方法,建议直接打开该模块文件,就55行代码,非常的简洁明了
- 查看三个模型对应的的controller文件,也非常简洁明了。。。
- 认证流程(via):
- 重置密码流程(via):
-
添加注册流程
-
创建Users Controller:
bin/rails g controller Users
# File: app/controllers/users_controller.rb class UsersController < ApplicationController allow_unauthenticated_access only: %i[ new create ] def new end def create @user = User.new(user_params) if @user.save redirect_to root_path, notice: "User was successfully created." else render :new end end private def user_params params.require(:user).permit(:email_address, :password, :password_confirmation) end end
- 创建view文件
#File: app/views/users/new.html.erb <%= tag.div(flash[:alert], style: "color:red") if flash[:alert] %> <%= tag.div(flash[:notice], style: "color:green") if flash[:notice] %>
Sign Up
<%= form_with(model:User) do |form| %> <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", placeholder: "Enter your email address", value: params[:email_address] %>
<%= form.password_field :password, required: true, placeholder: "Enter your password", maxlength: 72 %>
<%= form.password_field :password_confirmation, required: true, placeholder: "Confirm your password", maxlength: 72 %>
<%= form.submit "Sign up" %> <% end %> - 添加route
#File: config/routes.rb resources :users
-