Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is newly created or retrieved from database in Ruby on Rails

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?

like image 760
Schneems Avatar asked Dec 03 '25 10:12

Schneems


2 Answers

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 
like image 117
Joel AZEMAR Avatar answered Dec 05 '25 01:12

Joel AZEMAR


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

like image 23
tamersalama Avatar answered Dec 04 '25 23:12

tamersalama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!