gpt4 book ai didi

mysql - Sinatra:参数数量错误(4 代表 0..2)

转载 作者:行者123 更新时间:2023-11-28 23:55:42 26 4
gpt4 key购买 nike

我目前正在使用 SinatraActiveRecordMySQL 开发应用程序。我正在处理注册表单,它看起来像这样:

app.rb:

post '/signup' do
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret(params[:password], password_salt)

@usuarios = User.new(params[:nombre], params[:cedula], password_hash, "admin")
if @usuarios.save
redirect './signup', :notice => "Usuario creado exitosamente."
else
redirect './signup', :error => "Ha ocurrido un error, intente nuevamente."
end
end

View 看起来像这样,signup.erb:

    <form id="registro" action="/signup" method="POST">
<fieldset>
<legend>Ingrese sus datos</legend>
<label>Nombre
<input type="text" name="nombre">
</label>
<label>Cédula
<input type="text" maxlength="10" name="cedula">
</label>
<label>Contraseña
<input type="password" name="password">
</label>
<!-- TO-DO:
Dropdown list con los diferentes tipos de usuarios, i.e.: admin, secretario, etc.
-->
<input type="submit" id="registerButton" class="button small">Finalizar registro</a>
</fieldset>
</form>

每当我尝试创建一个新用户时,我都会收到以下错误:

ArgumentError - wrong number of arguments (4 for 0..2)

考虑到我要插入值的表有 4 列,我不明白为什么会出现此错误。

任何能帮助我解决这一不便的见解都将不胜感激!

提前致谢。

最佳答案

ActiveRecord::new方法只允许 2 个参数作为参数,它应该是一个散列。修复:

User.new(params[:nombre], params[:cedula], password_hash, "admin")

到:

User.new(nombre: params[:nombre], cedula: params[:cedula], password: password_hash, role: "admin")

你应该经常检查文档,在 99% 的情况下你可以找到问题:

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). In both instances, valid attribute keys are determined by the column names of the associated table – hence you can’t have attributes that aren’t part of the table columns.

 new(attributes = nil, options = {})

例子:

# Instantiates a single new object
User.new(:first_name => 'Jamie')

# Instantiates a single new object using the :admin mass-assignment security role
User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)

# Instantiates a single new object bypassing mass-assignment security
User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)

关于mysql - Sinatra:参数数量错误(4 代表 0..2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31759752/

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