Faker gem with seeds.rb

时间:2016-05-08 01:43:27

标签: ruby-on-rails refactoring faker

我希望重构我的seeds.rb文件。因此,我非常依赖gem faker来填充数据。

首先,我正在生成用户,如下所示:

# --== Generate Sample Users
  user_list = [
    [ "Name", "Lastname", "Password", 't', "email@something.tld", "Password"],
    [ "Mortimer", "Snerd", "Secret", 'f', "mortimer@snerd.net", "Secret"]
    5.times.do
      name = Faker::Name.first_name
      surname = Faker::Name.last_name
      password = Faker::Internet.password(10)
      [ name, surname, 'f', Faker::Internet.email(name + "." + surname), 'f', password, password]
    end
  ]
    user_list.each do |name, surname, admin, email, password, password|
      User.create( name:name, surname:surname, admin:admin,  email:email, password:password, password_confirmation:password )
    end

但是,我收到语法错误:unexpected tINTEGER, expecting ']' 5.times.do

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

首先,5.times.do不是有效的语法。 5.times返回一个Enumerable对象,但do不是一个方法。我认为你的意思是在这里使用do作为一个块。

此外,将块传递给times并不返回数组,它只返回块中返回的最后一项,因此您实际上并没有修改user_list数组

user_list = [
  [ "Name", "Surname", "Password", 't', "email@example.com", "Password"],
  [ "Mortimer", "Snerd", "Secret", 'f', "mortimer@snerd.net", "Secret"]
]

5.times.do
  name = Faker::Name.first_name
  surname = Faker::Name.last_name
  password = Faker::Internet.password(10)

  # Add user to user_list
  user_list << [ name, surname, 'f', Faker::Internet.email(name + "." + surname), 'f', password, password]
end

user_list.each do |name, surname, admin, email, password, password_confirmation|
  User.create(name: name, surname: surname, admin: admin,  email: email, password: password, password_confirmation: password_confirmation )
end

最后,您可能希望放弃使用Faker收发电子邮件,并使用find_or_create而不是create来阻止在用户已经存在给定电子邮件的情况下进行创建。你的seeds.rb应该是幂等的(不止一次运行它应该没有副作用)。