0

I'm using ActiveRecord with Ruby (no Rails) to interface with a SQLite3 database. I fetch some data from a web API and store it in the database using find_or_create_by(some_hash). This works fine as long as the some_hash data is unique. If the some_hash already exists in the database, then the find_or_create_by method fails and gives the following sql error: SQLite3::ConstraintException: PRIMARY KEY must be unique.

I expected the find_or_create method first checks my database to see if the data already exists and if it does, then it will not create a duplicate entry. However if it doesn't find the data, then and only then it will create a new entry. So why do I get that error when some_hash already exists in the database like it was trying to save a duplicate entry?

How can I work around this issue?

2 Answers 2

1

I don't know why its throwing that error at you, but if you want you can just break the method upinto its constituents:

A.create(some_hash) unless A.where(some_hash).present?

Hope that helps

Sign up to request clarification or add additional context in comments.

Comments

0

Here's what worked:

A.create(some_hash) unless A.where("id" => some_hash["id"]).exists?

For some reason, querying the database with some_hash resulted in false positives and therefore I had to explicitly specify just the id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.