Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make my seeds file Idempotent?

In my deployment process I am running my seeds file. I want this to be Idempotent so I can run it multiple times without any issue.

Currently I get PG primary key errors if I run it multiple times.

My seeds pattern looks like this:

user = User.create(.....)
user.save!

foo = Foo.create(....)
foo.save!

How can I make this Idempotent?

Is this the best way?

if( user.exists?(some_column: some_value) )
else
  # do insert here 
end 
like image 446
Blankman Avatar asked Jan 20 '26 17:01

Blankman


2 Answers

I believe you can make use of first_or_create

User.where(email: "[email protected]").first_or_create do |user|
  user.name = "John"
end

This will only create User with email = "[email protected]" if it doesn't exist or it will return you the instance of existing User.

This way you can avoid the Unique Key Violation

like image 72
Deepak Mahakale Avatar answered Jan 22 '26 05:01

Deepak Mahakale


You can try :

unless user.find_by(some_column: some_value)
    user.save!
end
like image 38
devoh Avatar answered Jan 22 '26 05:01

devoh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!