0

Let's say I have User(name, password, email, zip code) table and I want to generate User objects with random data.

Is there a command( to use on rails console), which does that? something like User.generate.

Omar Lahlou
  • 1,000
  • 9
  • 33

2 Answers2

3

After adding the Faker gem to your gemfile, add this to your user.rb file.

def self.generate_new
  name     = Faker::Name.name 
  password = "foobar"
  email    = Faker::Internet.email
  zip      = Faker::Address.zip 
  User.create!(name:     name,
               passowrd: password,
               email:    email,
               zip:      zip)
end 

After restarting your console, the command User.generate_new should run this command and generate a new user with random inputs.

nicholas79171
  • 1,203
  • 2
  • 15
  • 28
  • Is there a way to know in advance what are compulsory fields that need to be filled in before creating an object(I don't want to check the presence validations each time I want to create an object) – Omar Lahlou Jul 06 '15 at 17:39
  • Do you want to skip the validations? Or are you just trying to find all the fields associated with the user and have it fill in data automatically? – nicholas79171 Jul 06 '15 at 17:43
  • I am trying to find all the fields associated with the user and have it fill in data automatically – Omar Lahlou Jul 06 '15 at 17:46
  • @OmarLahlou I don't think that's possible. You can get column names [like this](http://stackoverflow.com/a/1291395/3251199) but getting variable types and such is not quite feasible, at least to my knowledge. You'll just have to add to this function whenever you add a new attribute. – nicholas79171 Jul 06 '15 at 17:48
1

Take a look at this gem: https://github.com/stympy/faker

It creates fake data for objects.

MurifoX
  • 14,991
  • 3
  • 36
  • 60