[英]Problems Passing Virtual Attributes to Model in Rails3
在将某些虚拟属性从表单传递到我们正在测试的基本用户名/密码生成器时,我们遇到了一些问题。
在第一个实例中,我们要以以下形式输入所需的用户名/密码:
= simple_form_for(@user, :method => :put, :url => url_for({:controller => :users, :action => :new_batch_create})) do |f|
= f.text_field :usercount, :placeholder => 'Number of Passwords'
= f.submit
在我们的用户模型中,我们有:
...
attr_accessor :usercount
def self.generate_batch
usercount.times do
username = ""
password =""
5.times { username << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
5.times { password << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
User.create!(:username => username, :password => password)
end
end
...
并在控制器中:
def new_batch_create
@user = User.generate_batch(params[:user][:usercount])
redirect_to root_path
end
但是,当我们点击提交时,我们最终会遇到ArgumentError:
wrong number of arguments (1 for 0)
app/models/user.rb:22:in `generate_batch'
app/controllers/users_controller.rb:38:in `new_batch_create'
如果我们从控制器操作中删除(params [:user] [:usercount]),则会得到以下信息:
undefined local variable or method `usercount' for #<Class:0x0000010177d628>
如果我们尝试:usercount,我们会得到:
undefined method `times' for :usercount:Symbol
救命!
您对new_batch_create的定义没有指定参数,但调用已指定。 您需要使它们融为一体。
def self.generate_batch(usercount)
usercount.times do
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.