Mellon
Mellon

Reputation: 38842

a question on database seed.rb

If I have the following code defined inside db/seeds.rb,

default_car=Car.create({:name=>'TOYOTA'})
User.create({:username=>'default_user', car_id=>default_car.id})

I know the default_car and the user instances will be stored into Database when I run "rake db:seed".

My question is, if I run 'rake db:seed' again, again and again(multiple times), will the same instances be stored to database with multiple copies or it only save the instance once into database no matter how many times I run rake db:seed?

Upvotes: 1

Views: 1483

Answers (3)

james2m
james2m

Reputation: 1580

This is a limitation of having a single seed file. I was finding this frustrating as the application grows you often want to add new seed data so you end up either doing what Pascal suggests or creating either migrations with data in them or rake tasks to load the seeds. To get round this I knocked up seedbank. So I combine this with Pascals approach so I can re-run the seeds but can also target specific ones if I want to.

Upvotes: 0

Pascal Van Hecke
Pascal Van Hecke

Reputation: 4546

Better solution:

default_car = Car.find_or_create_by_name 'TOYOTA'
user = User.find_or_create_by_username 'default_user'
user.car = default_car
user.save

That way you can run "rake db:seed" multiple times without having to drop the database manually every time.

Upvotes: 5

corroded
corroded

Reputation: 21564

depends on your models if you allow duplicate values. if you don't it will throw an error. what you do is to clear your db first before running seed via rake db:resetdb

Upvotes: -1

Related Questions