hello,
find_or_create_by has a different behaviour according to the existence of the instance in the database,
is it possible to know the resulting operation (find or create) which has been actually executed ?
thank you,
Fabrice
hello,
find_or_create_by has a different behaviour according to the existence of the instance in the database,
is it possible to know the resulting operation (find or create) which has been actually executed ?
thank you,
Fabrice
With find_or_create, I don’t believe there is a way.
You can certainly do it with find_or_initialize
winter = Tag.find_or_initialize_by_name("Winter")
winter.persisted? # true if record exists, false if it does not
Just a thought. Maybe you can use a call back before the record is saved to set up a virtual attribute based on the result of new_record?
Fabrice Fabrisss wrote in post #972422:
hello,
find_or_create_by has a different behaviour according to the existence of the instance in the database,
is it possible to know the resulting operation (find or create) which has been actually executed ?
Why do you care? What's your use case?
thank you,
Fabrice
Best,
Thank you for your answers,
I like the solution with the 'initialize' function but I still haven't tried it.
I have a counter which counts the number of new occurence I will insert in the database, that's why I want to be able to distinguish both cases,
Sincerely,
Fabrice
Please quote when replying.
Fabrice Fabrisss wrote in post #972838:
Thank you for your answers,
I like the solution with the 'initialize' function but I still haven't tried it.
I have a counter which counts the number of new occurence I will insert in the database, that's why I want to be able to distinguish both cases,
Please explain further. I strongly suspect that there is a better way to accomplish what you're trying to do -- perhaps having the count done on the DB side would be useful.
Sincerely,
Fabrice
Best,