Sinatra:错误的参数数量(4为0..2)

时间:2015-08-01 08:11:09

标签: mysql ruby activerecord sinatra

我目前正在使用 Sinatra ActiveRecord MySQL 开发应用。我正在处理注册表单,如下所示:

app.rb

    <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>

视图如下所示, signup.erb

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

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

public class CustomerInfoDeserializer extends JsonDeserializer<CustomerInfo> {

    private final Set<String> allowedFields;

    public CustomerInfoDeserializer(String... allowedFields) {
        Set<String> allowed = new HashSet<>(Arrays.asList(allowedFields));
        this.allowedFields = Collections.unmodifiableSet(allowed);
    }

    @Override
    public CustomerInfo deserialize(JsonParser jp, DeserializationContext dc) 
            throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String field = node.fieldNames().next();
        if (!allowedFields.contains(field)) {
            throw new JsonMappingException("Field '" + field + "' not allowed");
        }

        CustomerInfo info = new CustomerInfo();
        info.setInfoType(field);
        JsonNode dataNode = node.get(field);
        for (Iterator<String> it = dataNode.fieldNames(); it.hasNext();) {
            String name = it.next();
            info.addProperty(name, dataNode.get(name).asText());
        }

        return info;
    }  
}

考虑到我尝试插入值的表格有4列,我不明白为什么我会收到此错误。

非常感谢帮助我解决这一不便的任何见解!

提前致谢。

1 个答案:

答案 0 :(得分:1)

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(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)