开发者

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

开发者 https://www.devze.com 2023-03-14 20:16 出处:网络
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

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


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消