tisokoro
tisokoro

Reputation: 275

How can I generate fake data with Associations on seed.rb in Rails

I´m trying to generate fake data with its model associations. For example, a company (model) has many establishments (another model).

 #seeds.rb

 50.times do 
       { FactoryGirl.create(:company) }
       { FactoryGirl.create(:establishment) } 
 end

companies.rb factories

FactoryGirl.define do
  factory :company do
    sequence(:name) { FFaker::Name.name }
    sequence(:license) { FFaker::SSNMX.imss }
    sequence(:legal_name) { FFaker::Name.name }
    sequence(:billing_address) { FFaker::AddressFR.full_address }
    user
  end
end

establishments.rb factories

FactoryGirl.define do
  factory :establishment do
    sequence(:name) { FFaker::Name.name }
    sequence(:address) { FFaker::AddressFR.full_address }
    company
  end
end

The idea is to have each new company possess at least five establishments. In other words, that by using Company.establishment it returns an array that is not empty.

I found this old code here on SO from 2009 but it doesn´t work

100.times do
    Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])
end

Upvotes: 1

Views: 1023

Answers (1)

James
James

Reputation: 630

I'm not sure what the Ffaker module is, but I definitely reccomend the Faker gem. They have great documentation on how to use the module to generate fake data.

https://github.com/stympy/faker

You can even create rake tasks that will run your Faker script and create that data for you automatically. As far as a good Faker tutorial goes (And just using seed data in general) I recommend the following article:

http://sudharti.github.io/articles/using-faker-and-populator-rails/

Also as a side note, all of your seed data should be in seeds.rb. And you will want to to use the create method and use key value pairs to specify what your are popluating. For example if I was populating an order number I would do:

Order.create(order_number: 123456789)

In your code above, specifically FactoryGirl you are specifying symbols, but not their key value pair. That's just one side observation.

Upvotes: 1

Related Questions