Schneems
Schneems

Reputation: 15888

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?

Upvotes: 3

Views: 6793

Answers (5)

Ecuageo
Ecuageo

Reputation: 26

You can try find_or_initialize_by and then do the new_record? check. One thing to keep in mind is that a user could be created before you have the chance to save your new record. You also have that same issue with find_or_create_by but this might give a larger window for such a thing to happen.

user = User.find_or_initialize_by(email: params[:email])
if user.new_record?
  if user.save
    render json: user, status: :created
  else
    render json: { errors: @like.errors }, status: :unprocessable_entity
  end
else
  render json: user
end

Upvotes: 0

Nathan Pena
Nathan Pena

Reputation: 317

user_total = User.count
user = User.find_or_create_by_custom_stuff(params[:user])
if user_total == User.count
 #No new user was created, find method was used.
 ...
else
 #New user created, create method was used.
 ...
end

Upvotes: -1

tamersalama
tamersalama

Reputation: 4143

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

Upvotes: 3

Luke
Luke

Reputation: 4925

user = User.find_or_create_by_custom_stuff(params[:user])
if user.new_record?
  # record does not exist in datastore
else
  ...
end

Upvotes: -1

Joel AZEMAR
Joel AZEMAR

Reputation: 2536

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 

Upvotes: 17

Related Questions