I'm using Ruby on Rails and i have a find_or_create_by_custom_stuff method. However i would like to know if the object i get back was found, or was created. Something like this
user = User.find_or_create_by_custom_stuff(params[:user])
if user.was_found_from_database?
...
elsif user.was_recently_created?
...
end
Is there any way I can do this without relying on the created_at timestamp of the user?
You have the ActiveRecord method for that
@instance.new_record?
For you
user = User.find_or_create(params[:user])
user.new_record?
Note :
.new_record? => NOT RECORDED IN DATABASE
I would try not to use the find_or_create* method. The reason is that almost always the finder pattern will diverge from the creation one.
Another approach could be:
user = User.custom_finder(params)
if user.blank?
user = User.create(params)
#some business logic goes here
else
#other business logic goes here
end
This could also be implemented into the User model for better structure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With