Rails5:如何为种子参数设置变量

时间:2018-06-06 18:39:08

标签: ruby-on-rails

我正在为具有许多相似列的不同表播种多个csv。例如,教师和学生表具有相似的列电子邮件,名称等。所以我想通过将所有常见事物放入变量来缩短我的种子文件,以便:

puts "Seeding teachers.."
File.open("teachers.csv", "r") do |f|
  f.each_with_index do |line, index|
    email, name, teacher_code = line.chomp.split (",")    
  Teacher.create(email: email, name: name, teacher_code: teacher_code)
  end
end

puts "Seeding students.."
File.open("students.csv", "r") do |f|
  f.each_with_index do |line, index|
    email, name, subject = line.chomp.split (",")
  Student.create(email: email, name: name, subject: subject)
  end
end

变为:

def common_data
    [email, mame]
end

def common_params
    ["email: email", "name: name"] # not sure
end

puts "Seeding teachers.."
File.open("teachers.csv", "r") do |f|
  f.each_with_index do |line, index|
    common_data, teacher_code = line.chomp.split (",")    
  Teacher.create(common_params, teacher_code: teacher_code)
  end
end


puts "Seeding students.."
File.open("students.csv", "r") do |f|
  f.each_with_index do |line, index|
    common_data, subject = line.chomp.split (",")
  Student.create(common_params, subject: subject)
  end
end

我收到错误

NameError: undefined local variable or method `email' for main:Object

1 个答案:

答案 0 :(得分:2)

common_data中出现错误,是吗?因为,在这里:

[email, mame]

(假设“mame”应该是“name”)ruby希望email是变量或方法。但它不是,是吗?

也许你的意思是:

['email', 'name']

[:email, :name]