Reputation:
I am writing a Rake task to populate the database with some mock data that they have given to me, so for example if there is a Organization table that has a name, id and time_zone field I wanted to populate it in my rake task, so first I created an array of my sample Organizations:
SAMPLE_ORGANIZATIONS = [ '37 Signals', 'Fog Creek']
And then a method to populate database from that:
def create_organizations
SAMPLE_ORGANIZATIONS.each_with_index {|item, index|
Organization.first_or_create(
name: item,
time_zone: 'Central'
)
}
end
Is it a good way? How can I improve it?
Upvotes: 1
Views: 192
Reputation: 5301
There are a few options.
Put your mock code in db/seeds.rb, then run rake db:seed
Fixtures. Define the data in yaml files, then run rake db:fixtures:load
.
Factory Girl. Probably the best choice, but slightly more complicated. Put your FactoryGirl code in db/seeds.rb and use it like #1.
Upvotes: 2