播种数据库时参数数量错误

时间:2016-01-21 05:58:20

标签: ruby-on-rails-4

我有一个通过以下方法生成的模型

$ rails generate model user first_name last_name age:integer

然后我尝试使用seeds.rb中的以下内容填充数据库。

User.destroy_all

User.create![
    {first_name: "Vamsi", last_name: "Pavan", age: 21},
    {first_name: "Vani", last_name: "Pavani", age: 20}
]

当rake db:seed完成后,我收到以下错误。

rake aborted!
ArgumentError: wrong number of arguments (2 for 1)
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.5/lib/active_record/attribute_methods.rb:358:in `[]'
/home/gvpmahesh/code/rails/coursera/advanced_ar/db/seeds.rb:10:in `<top (required)>'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `block in load'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/railties-4.2.5/lib/rails/engine.rb:547:in `load_seed'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.5/lib/active_record/tasks/database_tasks.rb:250:in `load_seed'
/home/gvpmahesh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.5/lib/active_record/railties/databases.rake:183:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

2 个答案:

答案 0 :(得分:1)

在方法和参数之间忘记空间

User.create! [
    {first_name: "Vamsi", last_name: "Pavan", age: 21},
    {first_name: "Vani", last_name: "Pavani", age: 20}
]

或包装argiments ()

User.create!([
    {first_name: "Vamsi", last_name: "Pavan", age: 21},
    {first_name: "Vani", last_name: "Pavani", age: 20}
])

在这种情况下,您将在单个事务中创建所有对象(用户)

答案 1 :(得分:0)

只需遍历此数组的each项。

users = [
  {first_name: "Vamsi", last_name: "Pavan", age: 21},
  {first_name: "Vani", last_name: "Pavani", age: 20}
]

users.each{|user| User.create! user}