Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

When I run rake db:populate it never reaches 1000 it stops sometime before it gets there and because I'm using create! it shows me what I need to see which is: Usernname has already been registered.

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.

e.g.

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

like image 437
LondonGuy Avatar asked Jan 23 '12 01:01

LondonGuy


2 Answers

You could add an index to your loop.

1000.times do |n|
  username = Faker::Internet.user_name
  username = "#{username}_#{n}"
  ...
end
like image 195
Michelle Tilley Avatar answered Oct 24 '22 05:10

Michelle Tilley


This worked for me. Not quite sure why "n" creates numbers though.

 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
like image 32
LondonGuy Avatar answered Oct 24 '22 05:10

LondonGuy