尝试运行"rake db:populate"时"undefined local variable or method `n' for main:Object"



我正在学习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

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

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

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

相关内容

最新更新