简体   繁体   English

如何阻止faker gem在ruby on rails上失败的用户名唯一性验证?

[英]How can I stop faker gem from failing username uniqueness validation in ruby on rails?

Using faker to populate my database with fake users and I have a validation rule that makes sure usernames are unique and can't be registered more than once. 使用faker用假用户填充我的数据库,我有一个验证规则,确保用户名是唯一的,不能多次注册。

When I run rake db:populate it never reaches 1000 it stops sometime before it gets there and because I'm using create! 当我运行rake db:populate它永远不会达到1000它会在它到达之前的某个时间停止并且因为我正在使用create! it shows me what I need to see which is: Usernname has already been registered. 它向我展示了我需要查看的内容:Usernname已经注册。

My question is there a way I can add a number to the username and each time it comes back round the number increases? 我的问题是,有一种方法可以在用户名中添加一个数字,每次它都会在数字增加时回来吗? That way no username will ever be the same. 这样,没有用户名将是相同的。

eg 例如

john1 pete2 sally3 smith4 luke5 john6 sally7 john1 pete2 sally3 smith4 luke5 john6 sally7

etc... 等等...

or is there some other way to make sure no username comes up more than once? 或者是否有其他方法可以确保没有用户名出现多次?

 namespace :db do
      namespace :development do
        desc "Create user records in the development database."
        task :populate => :environment do
          require 'faker'

          1000.times do

            User.create!(
            :username => Faker::Internet.user_name,
            :email => Faker::Internet.email,
            :password => "greatpasswordhuh"
    )


          end
        end
      end
    end

Kind regards 亲切的问候

You could add an index to your loop. 您可以为循环添加索引。

1000.times do |n|
  username = Faker::Internet.user_name
  username = "#{username}_#{n}"
  ...
end

This worked for me. 这对我有用。 Not quite sure why "n" creates numbers though. 不太确定为什么“n”会创建数字。

 namespace :db do
        desc "Create user records in the development database."
        task :populate => :environment do
          require 'faker'

          100.times do |n|
            username = "#{Faker::Name.first_name}#{n}"
            User.create!(
              :username => username,
              :email => Faker::Internet.email,
              :password => "greatpasswordhuh"
            )

        end
      end
    end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM