Last Updated: September 09, 2019
·
744
· aanfuso

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.