当尝试运行“rake db:populate”时,“未定义的局部变量或方法`n'用于main:Object”

时间:2013-08-09 21:57:49

标签: ruby-on-rails ruby rspec rake

我正在阅读Michael Hartl的教程,我无法得到错误:

undefined local variable or method `n' for main:Object

当我运行bundle exec rake db:populate

sample_data.rake文件

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    name  = Faker::Name.name
    email = "example-#{n+1}@railstutorial.org"
    password  = "password"
    User.create!(name: name,
                   email: email,
                   password: password,
                   password_confirmation: password)
  end
end

2 个答案:

答案 0 :(得分:1)

您在电子邮件旁边有内插字符串,并且未在任何地方定义。删除或定义它。

答案 1 :(得分:1)

只需在脚本开头n之前将0变量初始化为name

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    n = 0
    name  = Faker::Name.name
    email = "example-#{n+1}@railstutorial.org"
    password  = "password"
    User.create!(name: name,
                   email: email,
                   password: password,
                   password_confirmation: password)
  end
end

这段代码可能用在一个循环中。在这里,您实际上不需要n