Search code examples
ruby-on-railsrubyrakeseed

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?


Solution

  • 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:

      MyClass.create if MyClass.count == 0

    3. Better solution might be to use find_or_create_by method. See the docs: http://easyactiverecord.com/blog/2014/03/24/using-find-or-create-with-multiple-attributes/