Avoid duplicate entries created with seeds.rb?

I have the following code in mine seeds.rb

to create an entry in my simple Rails application.

Post.create(
    title: "Unique Title!",
    body: "this is the most amazingly unique post body ever!"
  )

      

When running the command rake db:seed

, obviously the db seeds with this data. How to add validation or protection to the code so that it is included only once, i.e. How unique? If I restart rake db:seed

, I don't want to add this same entry again.

+3


source to share


3 answers


Try the following:

 Post.where( title: "Unique Title!",  body: "this is the most amazingly unique post body ever!").first_or_create

      



Hope this helps you.

+4


source


you can use a gem like seed_migration

or the_gardener

, or something else that creates versions of seeds and only runs them once.



most of them create seed files similar to migration files

+1


source


The way to quickly prevent this is to use find_or_create_by

.

Usage would look like:

Post.find_or_create_by(title: "Unique Title!", body: "this is the most amazingly unique post body ever!")

      

Here are the docs .

+1


source







All Articles