get'/users', to: 'users#index' get'/users/:id', to: 'users#show' post'/users', to: 'users#create' delete'/users/:id', to: 'users#destroy' patch '/users/:id', to: 'users#update'
class UsersController < ApplicationController def create user = User.new user.email = params[:email] user.password = params[:password] user.password_confirmation = params[:password_confirmation] ifuser.save render json: { resource: user }, status: 200 else render json: { errors: user.errors }, status: 400 end end end
第一步
1 2 3 4 5 6 7 8 9 10
class UsersController < ApplicationController def create user = User.new({ email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation] }) ifuser.save render json: { resource: user }, status: 200 else render json: { errors: user.errors }, status: 400 end end end
第二步使用 permit 方法
1 2 3 4 5 6 7 8 9 10
class UsersController < ApplicationController def create user = User.new params.permit(:email, :password, :password_confirmation) ifuser.save render json: { resource: user }, status: 200 else render json: { errors: user.errors }, status: 400 end end end
第三步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class UsersController < ApplicationController def create user = User.new create_params user.save render_resource user end
def create_params params.permit(:email, :password, :password_confirmation) end
def render_resource(resource) if resource.valid? render json: {resource: resource}, status: 200 else render json: {errors: resource.errors}, status: 400 end end end
第四步,使用 create 方法,等价于 先 new 再 save
1 2 3 4 5 6 7 8 9 10 11
classUsersController < ApplicationController defcreate user = User.create create_params render_resource user end
defcreate_params params.permit(:email, :password, :password_confirmation) end end # render_resource 方法已提升到 ApplicationController 中
第五步,很明显 user 声明了直接使用
1 2 3 4 5 6 7 8 9
classUsersController < ApplicationController defcreate render_resource User.create create_params end
defcreate_params params.permit(:email, :password, :password_confirmation) end end
发送邮件
bin/rails generate mailer UserMailer
app/mailers/user_mailer
1 2 3 4 5 6 7
classUserMailer < ApplicationMailer defwelcome_email(user) @user = user @url = 'https://www.baidu.com' mail(to:@user.email, subject:'Welcome to My Awesome Site') end end
app/mailers/application_mailer.rb
1 2 3 4
classApplicationMailer < ActionMailer::Base defaultfrom: '529743595@qq.com' layout 'mailer' end
class User < ApplicationRecord has_secure_password validates_presence_of :email validates_uniqueness_of :email validates_presence_of :password_confirmation, on: [:create]