Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: find_or_create_by equivalent that will not persist until save

I'm currently using this code block to retrieve a user or create a new one:

user = User.find_or_create_by!(email:params[:email])

However, I don't necessarily want to persist the new user to the database.

Is there something like "find_or_new_by" that will only persist upon:

user.save
like image 430
etayluz Avatar asked Jul 20 '15 21:07

etayluz


2 Answers

You seem to be looking for #find_or_initialize_by. Instead of calling create, the named method calls new. To save the object (assuming it is initialized, and not found), you will call save as you want.

And if you look at the source code for the method, it does exactly what you are looking for!

def find_or_initialize_by(attributes, &block)
  find_by(attributes) || new(attributes, &block)
end

On the docs page I provided with the method link, I was not able to find a bang (!) version of the method. Using the bang will raise an error. Depending on your use, you may not need it at all.

like image 91
onebree Avatar answered Nov 14 '22 22:11

onebree


try this

user = User.where(email: params[:email]).first_or_initialize

it will just initialize it if does not exists.

like image 29
Athar Avatar answered Nov 14 '22 23:11

Athar