Rails 设计:configure_permitted_pa​​rameters 未按预期工作

如何解决Rails 设计:configure_permitted_pa​​rameters 未按预期工作

我正在使用带有 API 版本控制的设计,当我尝试使用设计创建新用户时,它给了我(电子邮件不能为空,密码不能为空),我在网上搜索了很多解决方案,我找到了我需要为参数添加一个消毒剂,所以我将它添加到我的 application_controller.rb 但不幸的是它不起作用。

我会粘贴代码,请告诉我有什么问题?

提示:我需要原样的路线(

POST /api/v1/users(.:format) ---> devise/registrations#create {:format=>:json}

)

应用层次结构

  • 应用
    • 控制器
      • api
        • v1
          • 担忧
          • api_controller.rb
        • v2
      • application_controller.rb
    • 模型
      • user.rb
      • application_record.rb
  • 配置
  • 数据库
  • ...

app/controller/application_controller.rb

class ApplicationController < ActionController::API
  
  before_action :configure_permitted_parameters,if: :devise_controller?

  respond_to :json
  # Devise code

  protected
  # Devise methods
  # Authentication key(:username) and password field will be added automatically by devise.
  def configure_permitted_parameters
    added_attrs = [:name,:email]

    devise_parameter_sanitizer.permit(:sign_up,keys: added_attrs)
    devise_parameter_sanitizer.permit(:account_update,keys: added_attrs)
  end
end

config/routes.rb

require 'api_constraints.rb'

Rails.application.routes.draw do
  # For details on the DSL available within this file,see https://guides.rubyonrails.org/routing.html

  namespace :api,defaults: { format: :json }  do
    namespace :v1,constraints: ApiConstraints.new(version: 1,default: true) do

      # for APIs version,we will use the default devise controllers

      devise_for :users,controllers: {
                   :sessions => "devise/sessions",:passwords => "devise/passwords",:registrations => "devise/registrations",:confirmations => "devise/confirmations",:unlocks => "devise/unlocks"
               }
    end
  end
end

config/initializers/devise.rb

Devise.setup do |config|
  require 'devise/orm/active_record'

  config.case_insensitive_keys = [:email]

  config.strip_whitespace_keys = [:email]

  config.skip_session_storage = [:http_auth]

  config.stretches = Rails.env.test? ? 1 : 12

  config.reconfirmable = true

  config.expire_all_remember_me_on_sign_out = true

  config.password_length = 6..128

  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  config.reset_password_within = 6.hours
  
  config.sign_out_via = :delete
end

db/migrate/20210615223352_devise_create_users.rb

# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|

      t.string :name,null: false,default: ""
      t.datetime :date_of_birth
      t.string :status
      t.string :type
      t.string :nickname

      ## Database authenticatable
      t.string :email,default: ""
      t.string :encrypted_password,default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      # Trackable
      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
      t.string   :last_sign_in_ip

      # Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

      # Lockable
      t.integer  :failed_attempts,null: false # Only if lock strategy is :failed_attempts
      t.string   :unlock_token # Only if unlock strategy is :email or :both
      t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :users,:email,unique: true
    add_index :users,:reset_password_token,:confirmation_token,:unlock_token,unique: true
  end
end

db/schema.rb

ActiveRecord::Schema.define(version: 2021_06_15_223352) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "users",force: :cascade do |t|
    t.string "name",default: "",null: false
    t.datetime "date_of_birth"
    t.string "status"
    t.string "type"
    t.string "nickname"
    t.string "email",null: false
    t.string "encrypted_password",null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count",null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    t.integer "failed_attempts",null: false
    t.string "unlock_token"
    t.datetime "locked_at"
    t.datetime "created_at",precision: 6,null: false
    t.datetime "updated_at",null: false
    t.index ["confirmation_token"],name: "index_users_on_confirmation_token",unique: true
    t.index ["email"],name: "index_users_on_email",unique: true
    t.index ["reset_password_token"],name: "index_users_on_reset_password_token",unique: true
    t.index ["unlock_token"],name: "index_users_on_unlock_token",unique: true
  end

end

lib/api_constraints.rb

class ApiConstraints
  def initialize(options)
    @version = options[:version]
    @default = options[:default]
  end

  def matches?(req)
    @default ||
      (req.respond_to?('headers') &&
       req.headers.key?('Accept') &&
       req.headers['Accept'].eql?(
         "application/vnd.railsapibase.v#{@version}"))
  end
end

app/controllers/api/v1/api_controller.rb

class Api::V1::ApiController < ApplicationController

  include Concerns::Response
  include Concerns::ErrorHandler
  
end

Postman Images Test 1

Postman Images Test 2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res