简体   繁体   English

在Rails3中将虚拟属性传递给模型的问题

[英]Problems Passing Virtual Attributes to Model in Rails3

We're having some problems passing some virtual attributes from my form to a basic username / password generator we're testing. 在将某些虚拟属性从表单传递到我们正在测试的基本用户名/密码生成器时,我们遇到了一些问题。

In its first incarnation, we want to enter the number of usernames / password required in the form: 在第一个实例中,我们要以以下形式输入所需的用户名/密码:

= 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

In our user model, we have this: 在我们的用户模型中,我们有:

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

And in the controller: 并在控制器中:

  def new_batch_create
   @user = User.generate_batch(params[:user][:usercount])
   redirect_to root_path
  end

But when we hit submit, we end up with an ArgumentError: 但是,当我们点击提交时,我们最终会遇到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'

If we remove (params[:user][:usercount]) from the controller action, we get this: 如果我们从控制器操作中删除(params [:user] [:usercount]),则会得到以下信息:

 undefined local variable or method `usercount' for #<Class:0x0000010177d628>

And if we try :usercount, we get this: 如果我们尝试:usercount,我们会得到:

 undefined method `times' for :usercount:Symbol

Help! 救命!

Your definition of new_batch_create does not have a parameter specified, but the call does. 您对new_batch_create的定义没有指定参数,但调用已指定。 You need to bring those into harmony. 您需要使它们融为一体。

def self.generate_batch(usercount)
  usercount.times do
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM