faker-ruby / faker

A library for generating fake data such as names, addresses, and phone numbers.
MIT License
11.2k stars 3.18k forks source link

Fake relationship with a model #2307

Closed codechriscode closed 2 years ago

codechriscode commented 3 years ago

Is your feature request related to a problem? Please describe. Yes, in a way. The problem is we can't (or I have not found a standard way to) fake a relationship with another ActiveRecord model that's been previously 'seeded' (or planted, perhaps 😸 just kidding).

If you're adding new objects, please describe how you would use them Like adding multiple BankAccount that belongs_to a previously seeded User at random

Describe alternatives you've considered Using the example above to make it easier to understand. I considered creating an Array of some or all of the Users during their seeding process, so as to use them later when BankAccounts are seeded. But then I thought this could be part of faker (if it doesn't already exists)

Additional context I'm thinking about implementing something like this myself as a side project if I get the time to do it (and if there's no standard way to do it), so any advice you could share to get me started would be helpful

gabrielcosta42 commented 2 years ago

I think factory_bot is the gem you are looking for. It's possible to seed records with it's associations and still keep the random values from faker.

# factories/user.rb
FactoryBot.define do
  factory :user do
    name { Faker::Name.name }
  end
end

# factories/bank_account.rb
FactoryBot.define do
  factory :bank_account do
    user
    number { Faker::Number.number(digits: 11) }
  end
end

# db/seeds.rb
# seed users 
users = FactoryBot.create_list(:user, 5)

# manually associating with bank_account
users.each do |user|
  FactoryBot.create(:bank_account, user: user)
end

# seed bank_accounts with factory association
FactoryBot.create_list(:bank_account, 5)

For Rails apps use factory_bot_rails gem.

codechriscode commented 2 years ago

Cool, thanks @gabrielcosta42!