VoA
VoA

Reputation: 503

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?

Upvotes: 3

Views: 4549

Answers (2)

Joao Cunha
Joao Cunha

Reputation: 772

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/

Upvotes: 8

user229044
user229044

Reputation: 239301

It just runs the file. Rails does nothing for you, as far as preventing creation of duplicate seed data. If your file creates a record, it will attempt to create that record each time you seed. It's completely up to you to prevent this, in the case that you don't want duplicate seed data.

If you want to create a record unless it already exists, use find_or_create_by:

Project.find_or_create_by_title_and_description "foo", "bar"

This will create a Project with the given title and description unless it already exists, letting you run rake db:seed as many times as you want without creating duplicates.

Upvotes: 4

Related Questions