2

I used destroy to delete a record remotely in heroku rails console and now it does not show up if I write

 MyModel.find_by(email: '[email protected]')

but it does show up if I write

MyModel.find_by_or_create_by(email: '[email protected]')

...except the id is nil. I can't figure out how to get rid of this record. I am using postgres and rails 4

When I try to create a new record with the same email via the web ui, it triggers the uniqueness validation for this ghost record...yet I can't remove the ghost record.

1
  • 2
    I think its soft deleted. Check if there any soft deletion gems installed if so try find by including the deleted records scope. Commented Nov 11, 2016 at 5:48

2 Answers 2

3
+50

When find_or_create_by returns a record with a nil id, that suggests the find part is failing, and then the create part fails too with validation errors. What do you get from MyModel.find_or_create_by(email: '[email protected]').errors.full_messages? I'm guessing you see the same uniqueness validation error as you're seeing in the web console.

Is your app using a soft-delete approach, e.g. with a gem like acts_as_paranoid or permanent_records? Those gems change the behavior of destroy so that it does not issue a SQL DELETE command but instead sets a deleted_at column. They also hide soft-deleted records, so that may be why find_by isn't giving you anything. If this is what you're doing, you should make sure your uniqueness validation knows to ignore soft-deleted records. How to do that depends on your soft-delete implementation, but you might find some tips here.

You might want to try straight SQL to see what's really in your database, e.g. using the Heroku psql prompt or this Ruby code: MyModel.unscoped.where(email: "[email protected]")

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

1 Comment

Yes. acts_as_paranoid was the culprit
0

find_or_create_by will look for the record by the given parameters and create it if it can't be found. If there isn't an id field that means it isn't being saved and your problem is already solved.

1 Comment

It is not solved, as I can neither save the record I find or create a new one via the web interface. I have a uniqueness validation set on the email field and this record without an id prevents a new record with the same email from being created.

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.