使用Postman调用Rails API的Devise注册接口无报错但未创建用户
问题描述
我创建了一个仅API的Rails项目并添加了Devise User模型,尝试通过Postman发送POST请求完成用户注册,但数据库中并未保存新用户,同时接口也未返回任何错误信息。
Postman请求及参数截图显示了发送的POST注册请求和传入的参数。
ApplicationController配置(含额外许可属性)
class ApplicationController < ActionController::API before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters attributes = :name, { roles: [] } devise_parameter_sanitizer.permit(:sign_up, keys: attributes) devise_parameter_sanitizer.permit(:account_update, keys: attributes) end end
带验证规则的Devise User模型
class User < ApplicationRecord # 包含默认的Devise模块。其他可用模块包括: # :confirmable(邮箱验证)、:lockable(账号锁定)、:timeoutable(会话超时)、:trackable(登录追踪)和 :omniauthable(第三方登录) devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :name, presence: true # 验证姓名必填 validates :password, presence: true # 验证密码必填 validates :email, presence: true # 验证邮箱必填 validates :roles, presence: true # 验证角色必填 has_many :reservations, dependent: :destroy # 关联预约记录,删除用户时同步删除预约 has_many :vechiles, through: :group_entities # 关联车辆(注:原文拼写为vechiles,应为vehicles) end
Devise用户表迁移文件
class DeviseCreateUsers < ActiveRecord::Migration[7.0] def change create_table :users do |t| t.string :name, null: false # 姓名字段,不可为空 ## 数据库验证字段 t.string :email, null: false, default: "" # 邮箱,不可为空 t.string :encrypted_password, null: false, default: "" # 加密后的密码,不可为空 ## 密码重置相关 t.string :reset_password_token # 密码重置令牌 t.datetime :reset_password_sent_at # 密码重置邮件发送时间 ## 记住登录状态相关 t.datetime :remember_created_at # 记住登录状态的创建时间 ## 登录追踪(可启用) # t.integer :sign_in_count, default: 0, null: false # 登录次数 # t.datetime :current_sign_in_at # 当前登录时间 # t.datetime :last_sign_in_at # 上次登录时间 # t.string :current_sign_in_ip # 当前登录IP # t.string :last_sign_in_ip # 上次登录IP ## 邮箱验证(可启用) # t.string :confirmation_token # 邮箱验证令牌 # t.datetime :confirmed_at # 邮箱验证通过时间 # t.datetime :confirmation_sent_at # 邮箱验证邮件发送时间 # t.string :unconfirmed_email # 待确认邮箱(仅启用重新验证时使用) ## 账号锁定(可启用) # t.integer :failed_attempts, default: 0, null: false # 登录失败次数(仅当锁定策略为失败次数时启用) # t.string :unlock_token # 解锁令牌(仅当解锁策略为邮箱或两者时启用) # t.datetime :locked_at # 账号锁定时间 t.timestamps null: false # 创建时间和更新时间字段,不可为空 end add_index :users, :email, unique: true # 邮箱字段加唯一索引 add_index :users, :reset_password_token, unique: true # 密码重置令牌加唯一索引 # add_index :users, :confirmation_token, unique: true # 邮箱验证令牌加唯一索引(可启用) # add_index :users, :unlock_token, unique: true # 解锁令牌加唯一索引(可启用) end end
为用户表添加roles字段的迁移文件
class AddRolesToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :roles, :text, array: true, default: [] # 添加roles字段,类型为数组文本,默认值为空数组 end end
Routes.rb配置
# frozen_string_literal: true Rails.application.routes.draw do devise_for :users # 配置Devise的用户路由 # 根据Rails路由DSL文档定义应用路由(https://guides.rubyonrails.org/routing.html) resources :users, only: [:index] # 配置用户列表路由,仅允许index动作 # 定义根路径路由("/") # root "articles#index" end
内容的提问来源于stack exchange,提问作者Basem shamseldin
相关产品推荐
相关产品推荐

