我正在阅读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
答案 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
。