Find or Initialize objects RoR
If you need to find an object or create it if this doesn't exist, instead of using
unless @user = User.find_by(email: params[:email])
@user = User.new(email: params[:email])
end
you can use:
@user = User.where(email: params[:email]).first_or_initilize
That will return the first element that matches the conditions or initialize a new object with these params.
Written by Agustin Anfuso
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Activerecord
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#