Rails 3 - 参数数量错误(0表示1)

时间:2012-10-05 04:42:08

标签: ruby-on-rails-3

我正在尝试为我的应用程序构建身份验证系统

注册用户填写表格然后提交调用用户#signup

def signup  
    @user = User.new(params[:user])
    @user.password(params[:user][:password])
    @user.save 
end`

我的用户模型包含

def password(pass)
    @password=pass
    self.salt = User.random_string(10)
    self.hashed_password = User.encrypt(@password, self.salt)
end

尝试调试时,我检查了@user散列中包含的内容:

  • @user = User.new(params[:user])哈希包含我的参数exept'id','hashed_pa​​ssword'和'salt'(加上时间戳)之后

  • @user.password(params[:user][:password])后,哈希值包含'hashed_pa​​ssword'和'salt'的值

  • @ user.save返回

    UsersController#signup中的ArgumentError

    错误的参数数量(0表示1)

堆栈跟踪

Started POST "/users/signup" for 127.0.0.1 at Fri Oct 05 14:23:49 +1000 2012
Processing by UsersController#signup as HTML
  Parameters: {"user"=>{"last_name"=>"last", "first_name"=>"first", "login"=>"myusername", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"me@gmail.com", "dob(1i)"=>"1980", "dob(2i)"=>"4", "dob(3i)"=>"2"}, "authenticity_token"=>"R8/BNPox9F9rkUXZQ84xjnsplRjqLJYe35EtGjKEAWk=", "utf8"=>"✓", "commit"=>"Create User"}
   (0.1ms)  begin transaction
   (0.0ms)  rollback transaction
Completed 500 Internal Server Error in 10ms

ArgumentError (wrong number of arguments (0 for 1)):
  app/controllers/users_controller.rb:17:in `signup'
  app/controllers/users_controller.rb:16:in `signup'


  Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
  Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.1ms)
  Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (7.8ms)

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我猜你有一个名为password的列和/或你有一个引用:password的验证。

在这种情况下,问题是你已经用password(一个参数的设置器)覆盖了password(pass) - 隐式零参数getter。您应该将您的setter移动到password=,然后创建一个始终返回nil的getter:

def password
  nil
end

def password=(pass)
  @password = pass
  self.salt = User.random_string(10)
  self.hashed_password = User.encrypt(@password, self.salt)
end

作为奖励,这意味着您可以取消明确的密码设置调用,因为User.new(:password => 'xyz')会自动调用password=