dpg5000
dpg5000

Reputation: 363

Avoid duplicate records created via seeds.rb?

I have the following code in my seeds.rb to create a record in my simple Rails app.

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

When running the rake db:seed command it obviously seeds the db with this data. How do I add a check or safeguard in the code so that it only enters that once, i.e. as a unique? If I rerun rake db:seed, I don't want add that same entry again.

Upvotes: 3

Views: 2859

Answers (3)

Matheus Richard
Matheus Richard

Reputation: 734

A way to quickly prevent this is using find_or_create_by.

The usage would be like:

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

Here's the docs.

Upvotes: 5

rob
rob

Reputation: 2296

you can use a gem like seed_migration or the_gardener or something else which create versions of the seeds and run these only one time.

most of these creates seedfiles similar to the migration files

Upvotes: 1

Akshay Borade
Akshay Borade

Reputation: 2472

Try this :

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

Hope this will help you.

Upvotes: 5

Related Questions