VoA VoA - 2 years ago 133
Ruby Question

What happens when you run rake:db seed twice?

I'm new to rails and I haven't been able to find a definitive answer to this question.

Let's say I have

Project.create!([{title: "foo", description: "bar"}])

in my seeds.rb file and then run

$rake db:seed

twice. Would there be two near-identical entries in the database or would it override the initial entry?

Answer Source

It will duplicate.

If you want to run multiple times, but prevent duplication. I guess you could:

  1. Use validation in one key field like putting validate_uniqueness_of :key_attribute
  2. Test the count of your table like:


if myClass.count == 0
  1. Better solution might be to use find_or_create_by() method. See de docs: http://easyactiverecord.com/blog/2014/03/24/using-find-or-create-with-multiple-attributes/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download