Closed codechriscode closed 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.
Cool, thanks @gabrielcosta42!
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
thatbelongs_to
a previously seededUser
at randomDescribe 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 whenBankAccounts
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