gpt4 book ai didi

ruby-on-rails - rails 强参数意外将字符串转换为整数

转载 作者:行者123 更新时间:2023-12-04 01:53:56 24 4
gpt4 key购买 nike

我想用电话号码保存模型用户,但 rails 意外地将电话从字符串类型转换为整数类型

def create
@user = User.new(user_params)
if @user.save
log_in @user
user_response = {
'user_id' => @user.id
}
render json: user_response
else
render json: @user.errors, status: :unprocessable_entity
end
end

private
def user_params
params.require(:user).permit(:username, :phone, :password, :password_confirmation)
end

错误:

Parameters: {"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "phone"=>"12345678901", "username"=>"test", "user"=>{"username"=>"lv", "phone"=>"12345678901"}}

(0.1ms) BEGIN

User Exists (0.2ms) SELECT 1 AS one FROM `users` WHERE `users`.`phone` = **BINARY '18610012942'** LIMIT 1

(0.1ms) ROLLBACK

Completed 422 Unprocessable Entity in 6ms (Views: 0.2ms | ActiveRecord: 0.5ms)

谁能帮帮我?非常感谢。

更新:

迁移:

class AddPhoneToUsers < ActiveRecord::Migration
def change
add_column :users, :phone, :string, index: true
end
end

型号:

class User < ActiveRecord::Base
attr_accessor :remember_token

validates :phone, presence: true, length: {minimum: 11, maximum: 11},
uniqueness: true, format: {with: VALID_PHONE_REGEX}

end

最佳答案

你的控制台输出显示

{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "phone"=>"12345678901", "username"=>"test", "user"=>{"username"=>"lv", "phone"=>"12345678901"}} ,

应该是这样的:

{"user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "phone"=>"12345678901", "username"=>"test"}}

根据上面的form进行修改

关于ruby-on-rails - rails 强参数意外将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30752707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com