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
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.
try this
user = User.where(email: params[:email]).first_or_initialize
it will just initialize it if does not exists.
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