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

Sinatra: wrong number of arguments (4 for 0..2)

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

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

视图看起来像这样,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)

考虑到 table 我尝试插入的值有 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)