Find_or_create_by - id = nil when record exists

I am trying to use the ActiveRecord method find_or_create_by

and I need the ID of the returned record. This happens when this method creates a new record. However, if the record already exists, the identifier (along with the created_at

and columns updated_at

) is nil

. All other data comes back just fine. Why is this? I can see this in my database and I have an ID. When I use find_by

to get a record, the id is returned. Is this a bug or am I missing something?

+3


source to share


1 answer


I know this is an old question, but I had the same problem and it was a fairly simple user error.

id

your object will be nil

if no object is found for the selected attributes, but it cannot be fully instantiated (initialized and stored in db) as it fails validation.



TL; DR; If you use Model.find_or_create_by(attributes)

and terminate an object with id: nil

, check for errors on it, tweak your attributes and happy coding.

+1


source







All Articles