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

时间:2011-12-12 18:43:24

标签: ruby-on-rails

我们在将一些虚拟属性从我的表单传递到我们正在测试的基本用户名/密码生成器时出现了一些问题。

在第一个版本中,我们想要输入表格中所需的用户名/密码数量:

= 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

帮助!

1 个答案:

答案 0 :(得分:0)

您对new_batch_create的定义没有指定参数,但是调用了。你需要把它们融合在一起。

def self.generate_batch(usercount)
  usercount.times do
  ...
相关问题